首页 > 解决方案 > 我无法弄清楚为什么这个返回的列表中有空格

问题描述

我已经包含了整个问题陈述和使用的代码。当我尝试了 char_list 结构的两种替代形式时,它们都被包含并注释掉了;在这两种情况下,问题仍然存在。

为什么不' '.join()清理空间?

'''Write a password generator in Python. Be creative with how you generate passwords - strong passwords have a mix of lowercase letters, uppercase letters, numbers, and symbols. The passwords should be random, generating a new password every time the user asks for a new password. Include your run-time code in a main method.'''


import random

def password_generator():

  #char_str = '1234567890abcdefgh!@#$%(^)%($('
  #char_str = ['a', 'b', 'c', 'd', '1', '2', '3', '4']
  password = []
  length = int(input("How long should the password be?"))

  while len(password) < length:
    password.append(char_str[random.randint(0, len(char_str) - 1)])

  return(' '.join(password))

print(password_generator())

示例输出:% ) 0 4 d c f b % 7

标签: python

解决方案


您通过文字空格连接每个字符,这就是每个字符之间有空格的原因。要解决这个问题,您可以加入一个空字符串:

"".join(password)

或者,您也可以只构建一个字符串而不是列表:

password = ""
while len(password) < length:
    password += char_str[random.randint(0, len(char_str) - 1]

推荐阅读