HOWTO: Create a random alpha-numeric string in Python

Creating an alpha-numeric string in python is easy, but having a quick function you can call or import as a module is better!

This is very useful for things like password generators.

To see how to do this in Perl, check out this post: …howto-create-a-random-alpha-numeric-string-in-perl

To see how to do this in PHP, check out this post: …howto-create-a-random-alpha-numeric-string-in-php

def makeID(makeIDchars=6):
    import random, string
    def join(a,b): return a+b[int(random.randrange(len(b)))]
    makeIDpool = string.letters[0:52] + string.digits
    return ''.join(map((lambda y: join(x, makeIDpool)), range(makeIDchars)))

To call it, just set a variable equal to the return value. You can optionally pass a length to get a longer or shorter string.


This code sample:

print makeID()
print makeID(10)
print makeID(20)
print makeID(1)

Will print something like this:

Did you find this post useful or have questions or comments? Please let me know!

This entry was posted in How Tos, Programming, python. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *