Most lightweight way to create a random string and a random hexadecimal number

What is the most lightweight way to create a random string of 30 characters like the following?

ufhy3skj5nca0d2dfh9hwd2tbk9sw1

And an hexadecimal number of 30 digits like the followin?

8c6f78ac23b4a7b8c0182d7a89e9b1


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

>>> t1 = timeit.Timer("''.join(random.choice('0123456789abcdef') for n in xrange(30))", "import random")
>>> t2 = timeit.Timer("binascii.b2a_hex(os.urandom(15))", "import os, binascii")
>>> t3 = timeit.Timer("'%030x' % random.randrange(16**30)", "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.


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.