我试图在python中创建一个CD密钥生成器,并以四个块(每个4位长)生成密钥。我使用for循环从所有字母数字字符的列表中生成字符,并将它们附加到字符串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` dictionarycharset是一个有两个键的字典,一个用于大写字母和小写字母,另一个用于0-9的数字。
charset = {
'letters': 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz',
'digits': '0123456789'
}问题是,for循环不是生成4个字符,而是生成一个字符,我似乎不知道为什么。我可能遗漏了一些很明显的东西。
发布于 2017-11-05 13:22:23
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))发布于 2017-11-05 13:22:59
chunk1 = "",你能把它移到外部循环吗?
发布于 2017-11-05 13:23:55
问题是,您在循环中说是chunk1 = ""。这意味着,每次循环运行时,都会将变量重置为"“。只要把它放在循环之外,它就工作得很好:https://repl.it/Nlkj/0
https://stackoverflow.com/questions/47122028
复制相似问题