Random string of digits?

Steven D'Aprano steve+comp.lang.python at pearwood.info
Sun Dec 25 10:46:58 EST 2011


On Mon, 26 Dec 2011 00:54:40 +1100, Chris Angelico wrote:

> 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;

Use the Source, Luke, er, Chris :)

If I've read the source correctly, randint() will generate sufficient 
bits of randomness to ensure that the entire int is random.

http://hg.python.org/cpython/file/default/Lib/random.py



-- 
Steven



More information about the Python-list mailing list