我知道这个问题已经问了很多,但是我似乎无法从先前给出的答案中解决这个问题。
这是到目前为止我得到的。
import string
import random
print("---------Password Generator---------")
letterslc = string.ascii_letters
lettersupc = letterslc.upper()
numbers = string.digits
punctuation = string.punctuation
lengthofpass = input("How many characters would you like your password to be?")
lengthofpass = int(lengthofpass)
我希望密码由数字,字母和符号组成,密码长度取自用户输入。
我没有在这里和那里在线阅读的任何正式培训。我不知道从这里去哪里。
任何帮助都会很好。
要从给定的字母,数字和标点符号生成随机单词,可以使用random.choice
Documentation代码如下:
password = ''.join(random.choice(letterslc + lettersupc + numbers + punctuation) for _ in range(lengthofpass))
lengthofpass = 10
时的密码示例
9C-BOZT+)G
&ZXWn*>CDD
Ox'BJXxBHj
欢迎使用堆栈溢出!与它的外观相反,我们不一定要编写代码来修复您的错误,并且这个惊人的网站上的所有贡献者都在这里帮助您回答问题。
无论如何,对于您的问题,在生成实际密码之前,您可以对代码进行一些改进,例如将字符串转换为可以在密码中使用的大字符数组。您可以这样完成:
import string
# You don't need to use the .upper(), as ascii_letters already contains the uppercase letters
# You can use the list() function to turn a string into an array, splitting it per character
# You can use the + operator to merge strings together
validChars = list(string.ascii_letters + string.digits + string.punctuation)
此外,您不需要使用新行即可使用int()函数,您可以像这样将其包装在input()命令周围:
passLength = int(input("Pass length? "))
最后,用于实际生成密码。为此,可以使用for
循环遍历每个字母,然后从数组中选择一个字符。
passW = ""
for letter in range(passLength):
# random.choice() picks a random item from an array
# In this case, it's a random character from our list of valid characters
passW += random.choice(validChars)
您需要做的最后一件事是将密码打印到屏幕上,以便用户可以使用它:
print(passW)
我尚未测试以上任何代码,但这就是要点。请不要实际使用此代码生成随机密码,因此random
模块并不安全。相反,请使用可生成加密安全密码的模块,例如secrets模块。
有很多方法可以做到这一点。
执行此操作的一种方法是使用random.sample方法(尽管请注意,密码不能超过94个字符,因为样本大小不能大于总体大小)。
import string
import random
print("---------Password Generator---------")
letterslc = string.ascii_letters
#There is no need of the command below since string.ascii_letters already includes both lower case and upper case letters
#lettersupc = letterslc.upper()
numbers = string.digits
punctuation = string.punctuation
allchars = letterslc+numbers+punctuation
lengthofpass = input("How many characters would you like your password to be?")
lengthofpass = int(lengthofpass)
password = "".join(random.sample(allchars,lengthofpass))
print(password)
您还可以使用for循环或while循环,并使用random.choice方法在每次迭代时从所有字符的列表中选择一个随机字符。
import string
import random
print("---------Password Generator---------")
letterslc = string.ascii_letters
#There is no need of the command below since string.ascii_letters already includes both lower case and upper case letters
#lettersupc = letterslc.upper()
numbers = string.digits
punctuation = string.punctuation
allchars = letterslc+numbers+punctuation
lengthofpass = input("How many characters would you like your password to be?")
lengthofpass = int(lengthofpass)
password = ""
for _ in range(lengthofpass):
password += random.choice(allchars)
print(password)