Python附体

2024-04-26 01:12:04 发布

您现在位置:Python中文网/ 问答频道 /正文

尝试更改列表以便生成密码

passwordlength=int(input('Enter how long you would like the password')) # The user input 

for x in range(0,passwordlength):         
       password=''.join(characters)                
       print(password)

这就是我现在的工作。字符是我在列表中使用的。这是给我的输入列表重复的输入数字。你知道吗

每次我试着在列表中添加一个append,结果我都会倒退

任何帮助都将不胜感激


Tags: theyou密码列表inputpasswordlonglike
3条回答

对不起,这个问题不太清楚。你知道吗

以下是我在这里做出的假设:

  • passwordlength是一个整数,包含要截断的长度(在代码中)
  • characters是要用作密码的字符/数字的列表。e、 g.字符=['1'、'2'、'a'、'c'、'd']等

我不明白你想用for循环做什么?你知道吗

我相信下面这些应该是你想要的。你知道吗

password=''.join(字符)[0:passwordlength]

试着这样做:

passwordlength=int(input('Enter how long you would like the password')) # The user input 
characters=['1','2','3','4','5','a','b','b']
password=[]
for x in range(0,passwordlength):         
       password.append(characters[x])                

print(''.join(password))

我想random.sample可能就是你想要的:

from random import sample

passwordlength = int(input('Enter how long you would like the password')) # The user input 


password = ''.join(sample(characters,passwordlength))

或者切一片到passwordlength

password = ''.join(characters[:passwordlength]) 

要验证用户输入,我们可以使用try/except和while循环:

from random import sample

while True:
    try:
        password_length = int(input('Enter password length between 1-{}'.format(len(characters)))) # The user input
        if password_length > len(characters):
            print("Password is too long")
            continue
        password = ' '.join(sample(characters,password_length))
        break
    except ValueError:
         print("Please enter digits only")

如果字符列表中有int,则需要在加入之前mapstr。你知道吗

password = ' '.join(map(str,sample(characters,password_length)))

相关问题 更多 >