Thursday, June 12, 2025
HomePythonProducing a random string - Yasoob Khalid

Producing a random string – Yasoob Khalid


Okay, so, most of us have no idea generate random strings which embody letters and digits. This may be actually helpful for producing a password (or, , stuff to assist you in your plan for world domination). So how do we generate a random string? Have you ever ever heard of the string module out there in python? Likelihood is, you haven’t. So what does this module present us? Okay right here you go lets perceive this module by instance:

# first we now have to import random module as this
# gives the spine for our random string
# generator after which we now have to import the string
# module.

>>> import random
>>> import string

# now lets see what this string module present us.
# I wont be going into depth as a result of the python
# documentation gives ample info.
# so lets generate a random string with 32 characters.

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

One other instance with a operate:

>>> import string
>>> import random
>>> def random_generator(dimension=6, chars=string.ascii_uppercase + string.digits):
...    return ''.be part of(random.alternative(chars) for x in vary(dimension))
...
>>> random_generator()
'G5G74W'
>>> random_generator(3, "6793YUIO")
'Y3U'

So thats it for now. If you wish to additional discover the string module then go to the official documentation.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments