generate random digits with length of 5

Tim Chase python.list at tim.thechases.com
Sun Sep 28 17:02:55 EDT 2008


> Wondering if there is a better way to generate string of numbers with
> a length of 5 which also can have a 0 in the front of the number.

If you want to resample the same digit multiple times, either of these 
two will do:

 >>> from random import choice
 >>> ''.join(str(choice(range(10))) for _ in range(5))
'06082'

 >>> from string import digits
 >>> ''.join(choice(digits) for _ in range(5))
'09355'


If you need to prevent the digits from being reused

 >>> d = list(digits)
 >>> random.shuffle(digit)
 >>> ''.join(d[:5])
'03195'

I suspect that the zfill responses don't have the property of equally 
distributed "randomness", as the first digit may more likely be a zero. 
  The methods here should give equal probabilities for each choice in 
each place.

-tkc






More information about the Python-list mailing list