python - 列表不会第二次加入,但会第一次加入
问题描述
我想将列表转换为自动密码生成器的字符串,这是代码:
import random
import string
print("hello welcome to the random password generator! ")
level_of_password = input("what level do you want your password to be?(weak, medium, strong): ")
list_of_words_for_password = ["obama", "apples", "mom", "your", "cyber"]
if level_of_password == "weak":
weak_password = list(random.sample(list_of_words_for_password, 2))
weak_password = "".join(weak_password)
print(weak_password)
elif level_of_password == "medium":
letters_for_password = list(string.ascii_letters)
numbers_for_password = []
for i in range(random.randint(10, 30)):
numbers_for_password.append(random.randint(5, 10))
letters_and_numbers_for_password = numbers_for_password + letters_for_password
medium_password = [random.sample(letters_and_numbers_for_password, random.randint(5, 20))]
medium_password = "".join(medium_password)
对于弱密码,它将列表转换为字符串就好了,但对于中等密码,如果我尝试打印它,它会给我这个错误:
line 27, in <module>
medium_password = "".join(medium_password)
TypeError: sequence item 0: expected str instance, list found
为什么我可以像弱密码一样加入我的中等密码的字符列表。
另外,我自己学习python,如果你在代码中看到你无法忍受的东西,也请告诉我。
解决方案
查找内联评论
import random
import string
print("hello welcome to the random password generator! ")
level_of_password = input("what level do you want your password to be?(weak, medium, strong): ")
list_of_words_for_password = ["obama", "apples", "mom", "your", "cyber"]
if level_of_password == "weak":
weak_password = list(random.sample(list_of_words_for_password, 2))
weak_password = "".join(weak_password)
print(weak_password)
elif level_of_password == "medium":
letters_for_password = list(string.ascii_letters)
numbers_for_password = []
for i in range(random.randint(10, 30)):
numbers_for_password.append(random.randint(5, 10))
letters_and_numbers_for_password = numbers_for_password + letters_for_password
#------>
medium_password = random.sample(letters_and_numbers_for_password, random.randint(5, 20)) # remove extra []
# ^^^^ ^^^^
medium_password = "".join(map(str, medium_password)) # convert intergers to string
# ^^^^^^^^^^^^^^^^^^^^^^^^^
print(medium_password)
推荐阅读
- c - Leetcode 算法计算时间过长
- jfrog-cli - 如何在 jfrog AQL 中使用数字模式
- linux - 我们如何确定 ffmpeg 所需的依赖项
- c# - 从对象列表中复制特定项目,其索引列表对应于对象的 id
- mfc - 使用 TVITEMEX 代替 TVITEM 结构有什么好处?
- varnish - 无法开始使用 Varnish 和 Wordpress - 教程已过时?
- html - 对超链接使用“border-bottom”而不是“text-decoration”——它在语义上是否正确?
- php - 不能不安装任何包 throw pecl?
- javascript - 向未公开的收件人发送电子邮件 nodemailer
- python - Django 遍历关系