Python 2.6中的随机字符串(可以吗?) [英] Random strings in Python 2.6 (Is this OK?)

查看:161
本文介绍了Python 2.6中的随机字符串(可以吗?)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试寻找一种更pythonic的方式来在python中生成可扩展的随机字符串.通常,我看到类似

I've been trying to find a more pythonic way of generating random string in python that can scale as well. Typically, I see something similar to

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

如果要生成长字符串,它很烂.

It sucks if you want to generate long string.

一段时间以来,我一直在考虑random.getrandombits,并弄清楚如何将其转换为位数组,然后对其进行十六进制编码.使用python 2.6,我遇到了bitarray对象,该文档未记录.我以某种方式使它开始工作,而且看起来真的很快.

I've been thinking about random.getrandombits for a while, and figuring out how to convert that to an array of bits, then hex encode that. Using python 2.6 I came across the bitarray object, which isn't documented. Somehow I got it to work, and it seems really fast.

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

It generates a 50mil random string on my notebook in just about 3 seconds.

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指出,引起此问题的字符数是奇数.添加了新代码,以确保始终从十六进制发送偶数个十六进制数字.

heikogerlach pointed out that it was an odd number of characters causing the issue. New code added to make sure it always sent fromhex an even number of hex digits.

还是想知道还有没有比这更快的更好的方法了.

Still curious if there's a better way of doing this that's just as fast.

推荐答案

import os
random_string = os.urandom(string_length)

,如果您需要网址安全字符串:

and if you need url safe string :

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

(请注意,在这种情况下,random_string的长度大于string_length的长度)

(note random_string length is greatest than string_length in that case)

这篇关于Python 2.6中的随机字符串(可以吗?)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆