Generating a large random string

Chris feb04.20.netman at
Fri Feb 20 14:19:11 CET 2004

If you're looking to have a string that you can write to in a stream, like a
file, you might try StringIO

>>> import random, string
>>> from cString import StringIO

>>> s = StringIO()
>>> for i in xrange(1000000):

>>> len(s.getvalue())

This works fine for strings up to 10 MB, after that you might want to
consider stashing your data to disk and reading/writing in chunks.


"Andreas Lobinger" <andreas.lobinger at> wrote in message
news:4035DC5F.FBACD4F8 at
> Aloha,
> Andreas Lobinger schrieb:
> > How to generate (memory and time)-efficient a string containing
> > random characters?
> > d = [random.choice(string.letters) for x in xrange(3000)]
> > s = "".join(d)
> 1) Sorry for starting a new thread, but there were calls for more spec.
> 2) Thanks for all replies so far.
> To be more specific about
> - OS/availability of /dev/random
> Im looking for an elegant solution for all types. At the moment i'm
> developing in parallel on a slow (250MHz) i86/Win95 notebook, a typical
> i86/linux box and a couple of SUNs (up to 16GB main-mem...).
> - using random / crypto-safe-strings
> The use of random is intended, because it generates a known sequence.
> I can store the seed an re-generate the sequence any time, and afaik
> the sequence is OS/machinetype independent.
> As i wrote in the original post, the random string is only a prerequisite
> for another question.
> - What to do with the string
> I use the sting as a testpattern for a tokenizer/parser. So the usage
> of string.letters is only used as an example here.
> The main question was:
> How to concat a string without contantly reallocating it.
> Wishing a happy day

More information about the Python-list mailing list