python - Python 2.6 中的随机字符串(可以吗?)

标签 python random python-2.6

我一直在尝试寻找一种更 Pythonic 的方式来在 python 中生成随机字符串,它也可以扩展。通常,我会看到类似于

''.join(random.choice(string.letters) for i in xrange(len))

如果你想生成长字符串,那就太糟糕了。

我一直在考虑 random.getrandombits,并弄清楚如何将其转换为位数组,然后对其进行十六进制编码。使用 python 2.6 我遇到了未记录的 bitarray 对象。不知怎的,我让它工作了,而且看起来真的很快。

它会在大约 3 秒内在我的笔记本上生成一个 5000 万个随机字符串。

def rand1(leng):
    nbits = leng * 6 + 1
    bits = random.getrandbits(nbits)
    uc = u"%0x" % bits
    newlen = int(len(uc) / 2) * 2 # we have to make the string an even length
    ba = bytearray.fromhex(uc[:newlen])
    return base64.urlsafe_b64encode(str(ba))[:leng]

编辑

heikogerlach 指出是奇数个字符导致了这个问题。添加了新代码以确保它始终从十六进制发送偶数个十六进制数字。

仍然好奇是否有更好的方法来做这件事一样快。

最佳答案

import os
random_string = os.urandom(string_length)

如果你需要 url 安全字符串:

import os
random_string = os.urandom(string_length).hex() 

(注意在这种情况下,随机字符串长度大于字符串长度)

关于python - Python 2.6 中的随机字符串(可以吗?),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/785058/

相关文章:

python - 如何在numpy中获取非默认类型的随机整数数组

python - 使用 namespace 解析 XML

python - Jupyter 使用了错误版本的 python

python - 在pygame中获取图像单个像素的颜色

python - 如何使用Python在当前shell中设置环境变量?

python - 如何随机洗牌排列比 PRNG 周期更多的列表?

javascript - 用唯一的随机数填充数组javascript

python - 有没有办法将 python 字典文字评估为有序字典?

python - 为什么这个 python UDP 套接字被重置为 'None' ?

python dataframe 做类似 oracle connect_by 的事情吗?