Generating a large random string
Chris
feb04.20.netman at spamgourmet.com
Fri Feb 20 13:38:19 EST 2004
I suppose this would be cheating?
>>> import random, sys
>>> class ReallyRandomString:
"Hey Rocky, watch me pull a random string out of my hat!"
def __init__(self, item):
self.__item = item
def __getitem__(self, key):
if type(key) is int:
return random.choice(self.__item)
elif type(key) is slice:
return ''.join([random.choice(self.__item)
for i in xrange(*key.indices(sys.maxint))])
else:
raise TypeError('Time to get a new hat!')
>>> ReallyRandomString('spam')[1000:1060]
'mapsmpspapaaamppmapammaasapmaspmspmpppmpmamsmpsaspamaamssspm'
Chris
"Roger Binns" <rogerb at rogerbinns.com> wrote in message
news:v99gg1-g7g.ln1 at home.rogerbinns.com...
> > > How to generate (memory and time)-efficient a string containing
> > > random characters?
>
> It depends how random you need it to be.
>
> The approach I take in my test harness (which generates a CSV file
> with random contents) is to create a 30,000 character string the
> old fashioned way:
>
> "".join([random.choice(item) for i in range(30000)])
>
> item is a string of which characters to choose from (some fields
> are phone numbers, some are names, some are email addresses etc).
>
> To generate a random string I then take random slices of that
> 30,000 character object. If I need longer strings, I glue
> the random slices together (in a cStringIO).
>
> Roger
>
>
More information about the Python-list
mailing list