tags:

views:

146

answers:

4

what is the most lightweight way to create a random string of 30 characters like this ? :

ufhy3skj5nca0d2dfh9hwd2tbk9sw1

and an hexadecimal number of 30 digits like this ?:

8c6f78ac23b4a7b8c0182d7a89e9b1

+3  A: 
import string
import random
lst = [random.choice(string.ascii_letters + string.digits) for n in xrange(30)]
str = "".join(lst)
print str
ocwbKCiuAJLRJgM1bWNV1TPSH0F2Lb
joefis
and random.choice(string.hexdigits)
joefis
+2  A: 

30 digit hex string:

>>> import os,binascii
>>> print binascii.b2a_hex(os.urandom(15))
"c84766ca4a3ce52c3602bbf02ad1f7"

The advantage is that this gets randomness directly from the OS, which might be more secure and/or faster than the random(), and you don't have to seed it.

wump
that's interesting, and probably a good choice for generating the 30 digit hex number he wants. probably could use urandom and a slice operator to generate the alphanumeric string also.
joefis
I did take a look at the other functions in binascii, they do have base64 and uuencode, but no way to generate the first kind of strings he wants (base36).
wump
+2  A: 

Incidentally, this is the result of using timeit on the two approaches that have been suggested:

Using random.choice():

>>> t1 = timeit.Timer("''.join(random.choice(string.hexdigits) for n in xrange(30))", "import random, string")
>>> t1.timeit()
69.558588027954102

Using binascii.b2a_hex():

>>> t2 = timeit.Timer("binascii.b2a_hex(os.urandom(15))", "import os, binascii")
>>> t2.timeit()
16.288421154022217
David Narayan
+4  A: 

I got a faster one for the hex output. Using the same t1 and t2 as above:

>>> t1 = timeit.Timer("''.join(random.choice(string.hexdigits) for n in xrange(30))", "import random, string")
>>> t2 = timeit.Timer("binascii.b2a_hex(os.urandom(15))", "import os, binascii")
>>> t3 = timeit.Timer("'%030x' % random.randrange(256**15)", "import random")
>>> for t in t1, t2, t3:
...     t.timeit()
... 
28.165037870407104
9.0292739868164062
5.2836320400238037

t3 only makes one call to the random module, doesn't have to build or read a list, and then does the rest with string formatting.

jcdyer
Nice. Just generate a random number 30 hex digits long and print it out. Obvious when pointed out. Nice one.
joefis
Interesting, I kind of forgot that Python (and the random module) handles bigints natively.
wump