【问题标题】:Why can't I get more than 59 characters as output in this code?为什么我不能在此代码中输出超过 59 个字符?
【发布时间】: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这个吗?具体来说,通过在迭代时打印出escolharand_alfa.find(escolha)len(rand_alfa) 的值。
  • >>> len(numeros_alfanum) >>> 59

标签: python random limit string-length chr


【解决方案1】:

您的 3 个已初始化的字母数字列表填充不正确。具体来说,您正在尝试使用以下值填充它们:

  • 97-122 ('a'-'z')
  • 65-90 ('A'-'Z')
  • 48-57 ('0'-'9')

问题是 range(x,y) 函数不包含y。所以,你错过了每个人的最后一个角色。相反,写:

num_alfanumericos1 = [x for x in range(97,123)]
num_alfanumericos2 = [x for x in range(65,91)]
num_alfanumericos3 = [x for x in range(48,58)]

注意:您还可以将范围转换为列表,如下所示:

num_alfanumericos1 = list(range(97,123))

【讨论】:

    猜你喜欢
    • 2017-01-03
    • 1970-01-01
    • 1970-01-01
    • 2011-03-31
    • 2013-10-25
    • 2023-03-07
    • 1970-01-01
    • 2016-11-30
    • 1970-01-01
    相关资源
    最近更新 更多