Source

Generating a random string

Okay, so, most of us do not know how to generate random strings which include letters and digits. This can be really useful for generating a password (or, you know, stuff to aid you in your plan for world domination). So how do we generate a random string? Have you ever heard of the string module available in python? Chances are, you haven’t. So what does this module provide us? Okay here you go lets understand this module by example:

# first we have to import random module as this
# provides the backbone for our random string
# generator and then we have to import the string
# module.

>>> import random
>>> import string

# now lets see what this string module provide us.
# I wont be going into depth because the python
# documentation provides ample information.
# so lets generate a random string with 32 characters.

>>> random = ''.join([random.choice(string.ascii_letters + string.digits) for n in xrange(32)])
>>> print random
'9fAgMmc9hl6VXIsFu3ddb5MJ2U86qEad'
>>> print len(random)
32

Another example with a function:

>>> import string
>>> import random
>>> def random_generator(size=6, chars=string.ascii_uppercase + string.digits):
...    return ''.join(random.choice(chars) for x in range(size))
...
>>> random_generator()
'G5G74W'
>>> random_generator(3, "6793YUIO")
'Y3U'

So thats it for now. If you want to further explore the string module then go to the official documentation.

Newsletter

×

If you liked what you read then I am sure you will enjoy a newsletter of the content I create. I am also publishing my "Practical Python Projects" book soon. To stay updated regarding the book and new posts, join 5000+ other people who receive my newsletter:

I send out the newsletter once every couple of weeks. No spam, I promise

✍️ Comments

ansh bansal

Your first example overshadows the in-built random. So it is a really bad idea. Also wouldn’t you consider changing the theme? It is like that I am reading a page through a magnifying glass.

Xploit

Helped me Generate random Device ID’s, Thanks

Constantin
In reply to Xploit

You may use Python’s built-in uuid module for this.

Say something

Send me an email when someone comments on this post.

Thank you!

Your comment has been submitted and will be published once it has been approved. 😊

OK