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 something else just use your evil mind. Okay so how do we generate a random string. Have you ever heard of the string module available in python ? The chances are that you have not heard about it. 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
>>> print len(random)

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()
>>> random_generator(3, "6793YUIO")

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


One thought on “Generating a random string.

  1. 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.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s