Random string of digits?

Chris Angelico rosuav at gmail.com
Sun Dec 25 08:54:40 EST 2011


On Mon, Dec 26, 2011 at 12:48 AM, Steven D'Aprano
<steve+comp.lang.python at pearwood.info> wrote:
> On Sun, 25 Dec 2011 08:30:46 -0500, Roy Smith wrote:
>
>> I want to create a string of 20 random digits (I'm OK with leading
>> zeros).  The best I came up with is:
>>
>> ''.join(str(random.randint(0, 9)) for i in range(20))
>>
>> Is there something better?
>
> '%20d' % random.randint(0, 10**20-1)

I should mention that this sort of thing is absolutely acceptable in
situations where you don't actually need that level of randomness; if
you want to assign 20-digit numbers to each of ten million objects,
you can happily use something that's only really random to fifteen. I
use this technique with base 36 numbers to generate arbitrary
alphanumeric strings to use as message tags, for instance; fill out a
specified field size, even though not every combination will actually
be used.

ChrisA



More information about the Python-list mailing list