首页 > 解决方案 > 列表不会第二次加入,但会第一次加入

问题描述

我想将列表转换为自动密码生成器的字符串,这是代码:

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,如果你在代码中看到你无法忍受的东西,也请告诉我。

标签: pythonstringlistpasswords

解决方案


查找内联评论

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)

推荐阅读