2 回答
TA贡献1877条经验 获得超1个赞
我认为最后一部分让你感到困惑。您正在使用chars正确数量的特定字符构建变量,但最后您再次在它们之间进行选择。
你可以改变:
for p in range(passlen):
password += random.choice(chars)
和
# option 1 - works better if working with lists
list_chars = list(chars)
random.shuffle(chars)
password = "".join(list_chars)
# option 2 - simpler solution for strings
password = "".join(random.sample(char, len(char)))
您还可以使用 shuffle 来选择之前的字符,而不使用 for 循环,例如:
# for this to work your `charslet` must be a list
random.shuffle(charslet)
chars += "".join(charslet[:passlet])
TA贡献1836条经验 获得超3个赞
这是更正后的代码:
import random
charslet ="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
charsnum = "1234567890"
charssym = "!@#$%^&*"
def password():
pwd = ""
passlen = int(input("How long do you want the password to be?: "))
passlet = int(input("How many letters do you want in your password?: "))
passnum = int(input("How many numbers do you want in your password?: "))
passsym = int(passlen - (passlet + passnum))
chars = ""
for let in range(passlet):
chars += random.choice(charslet)
for num in range(passnum):
chars += random.choice(charsnum)
for sym in range(passsym):
chars += random.choice(charssym)
list_chars = list(chars)
random.shuffle(list_chars)
pwd = "".join(list_chars)
print(pwd)
password()
我替换:
for p in range(passlen):
password += random.choice(chars)
和
list_chars = list(chars)
random.shuffle(list_chars)
pwd = "".join(list_chars)
将更改后的chars变量放入列表中可以让我对其进行洗牌、随机化并允许我将其分配给pwd
添加回答
举报