Python追加列表
尝试更改列表以便生成密码Python追加列表,python,list,input,Python,List,Input,尝试更改列表以便生成密码 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) 这就是我现在的工作。我在列表中使用的是字符。这是给我的
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)
这就是我现在的工作。我在列表中使用的是字符。这是给我的输入列表重复的输入号码
每次我尝试在列表中添加一个附加项时,结果都是倒退
任何帮助都将不胜感激这里有一些是模拟设置。其中choice将从列表中随机选择一项
from random import choice
myaplha = #somelist of letters to choice from
password = int(input("Enter password length")):
passw = []
for i in range(password):
passw.append(choice(myaplha))
print("".join(passw))
或
试着这样做:
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))
对不起,这个问题不是很清楚 以下是我在这里做出的假设:
- passwordlength是一个整数,包含要截断的长度(在代码中)
- characters是要用作密码的字符/数字的列表。e、 g.字符=['1','2','a','c','d']等
from random import sample
passwordlength = int(input('Enter how long you would like the password')) # The user input
password = ''.join(sample(characters,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,则需要在加入之前将映射到str
password = ' '.join(map(str,sample(characters,password_length)))
你能解释一下你期望的密码是什么吗?例如,您是否希望字符串的长度passwordlength
仅从字符中随机选择?字符是什么?我列出的列表中有很多数字和字母,我每次都会随机化。字符是一个数字和字母的列表。您只需不断为列表中的连接元素分配密码,您希望发生什么?也许password=''。join(characters[:passwordlength])
是您想要的。我更喜欢第一个建议。@Padraic可能应该在示例周围检查或尝试一下输入长度>len(characters)
。。。对于第二种情况,为了处理这种情况,您可以在slice@JonClements,没错,让我一如既往地诚实;)@帕德里亚克。。。嗯。。。一个太多了,除了。。。我会把长度检查和错误以及一个继续
,让ValueError
处理int
失败…@JonClements,是的,我想这更多是为了我自己的娱乐。运行代码,你会看到我提供的任何一种方法都会给你一个随机生成的密码,长度由用户指定。原始问题中的代码不会生成随机密码,至少不会像写的那样。很公平,只是提供了变化。好的。。。最新的编辑是一次公平的尝试,但是您在“
之后缺少了一个
,并且范围不是str
等。感谢您的捕获。并且OP似乎正在使用打印
函数和int(输入(…)
因此,您可能缺少一个int
来确保范围
没有得到一个stringfixed,我假设python2如果使用input()而不是raw\u input()将int字符串转换为int
password = ' '.join(map(str,sample(characters,password_length)))