python - 我无法弄清楚为什么这个返回的列表中有空格
问题描述
我已经包含了整个问题陈述和使用的代码。当我尝试了 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
解决方案
您通过文字空格连接每个字符,这就是每个字符之间有空格的原因。要解决这个问题,您可以加入一个空字符串:
"".join(password)
或者,您也可以只构建一个字符串而不是列表:
password = ""
while len(password) < length:
password += char_str[random.randint(0, len(char_str) - 1]
推荐阅读
- blueprism - 无法加载无法识别的应用程序类型浏览器启动
- tcp - Sim7080G 模块在使用 GNSS 时无法通过 TCP 发送数据
- windows - windows/delphi 中的 Alpha 3 语言扩展从哪里获取?
- swift - 如何快速删除滚动视图侧边栏
- c - 哪种方法更适合在 C 中的循环中递增和遍历
- java - 调用 CRUD 存储库时 Spring AutoWire 不起作用
- python - 将 python 脚本与 HTML 输入页面链接
- python - 为什么单独线程中的“face_recognition”包会减慢 UI 线程?
- css - 在桌面上呈现移动优先网站的正确方法
- javascript - 尝试将json文件中的结果格式化为html