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
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
import string
import random
lst = [random.choice(string.ascii_letters + string.digits) for n in xrange(30)]
str = "".join(lst)
print str
ocwbKCiuAJLRJgM1bWNV1TPSH0F2Lb
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.
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
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.