我正在尝试在python中创建一个CD密钥生成器,我正在生成四个块的密钥,每个长4个数字。我正在使用for循环从所有字母数字字符列表中生成字符,并将它们附加到字符串@import './../your_file_path/your_file_name.css';
。
chunk1
# 4 digits to be generated
for i in range(0, 4):
chunk1 = ""
# Choose randomly whether the next character will be a letter or digit
uld = randint(0, 1)
if uld == 0:
character = 'letters'
# Randomly choose a letter from all upper- and lowercase letters
selector = randint(0, 51)
elif uld == 1:
character = 'digits'
# Randomly choose a digit from 0-9
selector = randint(0, 9)
# Set `chunk1` equal to itself and append the selected digit
chunk1 = chunk1 + charset[character][selector] # References the `charset` dictionary
是一个包含两个键的字典,一个用于大写和小写字母,另一个用于0-9的数字
charset
问题是charset = {
'letters': 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz',
'digits': '0123456789'
}
循环不生成4个字符,而只是一个,我似乎无法弄清楚原因。我可能会遗漏一些相当明显的东西。
答案 0 :(得分:2)
chunk1
。
相反,您应该将值存储在列表中。 您也不需要所有这些字符串连接
output = []
for i in range(0, 4):
# Choose randomly whether the next character will be a letter or digit
uld = randint(0, 1)
if uld == 0:
character = 'letters'
# Randomly choose a letter from all upper- and lowercase letters
selector = randint(0, 51)
elif uld == 1:
character = 'digits'
# Randomly choose a digit from 0-9
selector = randint(0, 9)
output.append(charset[character][selector])
print(''.join(output))
答案 1 :(得分:0)
chunk1 = ""
你可以将它移到外面进行循环。
答案 2 :(得分:0)
问题是,你在循环中说chunk1 = ""
。这意味着,每次循环运行时都将变量重置为“”。只需将它放在循环之外,它就可以正常工作:https://repl.it/Nlkj/0