【发布时间】:2021-12-03 00:16:14
【问题描述】:
我正在尝试创建一个代码来训练我的 python 技能,它是一个程序,通过将它们从 ASCII 转换为字符来生成带有字母数字字符的随机字符串,然后它将与实际进行比较正常字母的顺序和加密消息,方法是按照每个字符串(字母和随机生成的字母)的索引号以随机顺序将正常字母替换为随机字母。 这是我遇到问题的部分:生成随机字母表
import random as r
# Here's the lower case
num_alfanumericos1 = [x for x in range(97,122)]
# Here's the upper case
num_alfanumericos2 = [x for x in range(65,90)]
# Here's the numbers
num_alfanumericos3 = [x for x in range(48,57)]
# I did it this way because I'll need to use the random.choice function that accepts int
numeros_alfanum = num_alfanumericos1 + num_alfanumericos2 + num_alfanumericos3
# Here's the actual order
alfanum='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
simbolos='!@#$%¨&*<>,.;:^~`´/+-'
rand_alfa=''
while len(rand_alfa)<62:
escolha = r.choice(numeros_alfanum)
escolha = chr(escolha)
if rand_alfa.find(escolha)==-1:
rand_alfa = rand_alfa + escolha
print(rand_alfa)
这不是一个简单的字母表,我包括了小写字母、大写字母和数字。列表的总长度为 62,但代码仅在我将 59 放入“while”语句之前有效:
while len(rand_alfa)<59:
我不知道它发生了什么,它根本不运行。我在 Spyder 和 Jupyter Notebook 上运行它,但在这两个问题上都是一样的。 我注意到 jupyter 用这段代码表示一个无限循环......但我不确定。 请帮我。哈哈
【问题讨论】:
-
你有debugged这个吗?具体来说,通过在迭代时打印出
escolha、rand_alfa.find(escolha)和len(rand_alfa)的值。 -
>>> len(numeros_alfanum) >>> 59
标签: python random limit string-length chr