列表不会第二次加入,但会第一次加入

a list will not join the scond time but will the first time

我想将一个列表转换为字符串以用于自动密码生成器 这是代码:

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)