我一直在尝试找到一种更 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 指出是奇数个字符导致了这个问题。添加了新代码以确保它始终从十六进制发送偶数个十六进制数字。
仍然很好奇是否有更好的方法来做到这一点同样快。