Generate Random String in Python

August 11, 2010

Here's a simple way to generate a random string in Python. I was using this to add an "unguessable" suffix onto a jpg filename so that it was not possible to guess the filename from the browser.

lRandomSuffix = ''.join(random.choice(string.letters + string.digits) for i in xrange(8))

This creates a random string, made up of letters (upper and lowercase) and numbers, that is 8 characters long.


Tags: random python