Efficiently generate a 16-character, alphanumeric string

ensnare picture ensnare · Mar 24, 2010 · Viewed 82.7k times · Source

I'm looking for a very quick way to generate an alphanumeric unique id for a primary key in a table.

Would something like this work?

def genKey():
    hash = hashlib.md5(RANDOM_NUMBER).digest().encode("base64")
    alnum_hash = re.sub(r'[^a-zA-Z0-9]', "", hash)
    return alnum_hash[:16]

What would be a good way to generate random numbers? If I base it on microtime, I have to account for the possibility of several calls of genKey() at the same time from different instances.

Or is there a better way to do all this?

Answer

David Schumann picture David Schumann · Jun 11, 2015

As none of the answers provide you with a random string consisting of characters 0-9, a-z, A-Z: Here is a working solution which will give you one of approx. 62^16 = 4.76724 e+28 keys:

import random, string
x = ''.join(random.choice(string.ascii_uppercase + string.ascii_lowercase + string.digits) for _ in range(16))
print(x)

It is also very readable without knowing ASCII codes by heart.

There is an even shorter version since python 3.6.2:

import random, string
x = ''.join(random.choices(string.ascii_letters + string.digits, k=16))
print(x)