Generating a large random string
Paul Rubin
http
Thu Feb 19 20:05:22 EST 2004
Andreas Lobinger <andreas.lobinger at netsurf.de> writes:
> How to generate (memory and time)-efficient a string containing
> random characters? I have never worked with generators, so my solution
> at the moment is:
What do you want to do with the random characters, and what OS are you
running on?
> import string
> import random
If you're using the random characters for some security-related purpose,
you shouldn't use the random module.
If you're running Linux or *BSD, the simplest way to get good quality
random characters is something like
s = open("/dev/urandom").read(3000)
or however many characters you want. For Windows, it's harder.
> random.seed(14)
> d = [random.choice(string.letters) for x in xrange(3000)]
> s = "".join(d)
> print s
> which is feasible for the 3000, but i need lengths in the range
> 10.000 to 1.000.000.
Try something like:
import array
from random import randint
d = array.array('B')
for i in xrange(1000000):
d.append(randint(0,255))
s = d.tostring()
More information about the Python-list
mailing list