In this tutorial, we are going to learn how we can generate a random string for different purposes. For example, if we want to send an OTP, we have to provide a different string every time an OTP has to be sent. Or may be for custom Captcha purpose you need to generate random string values.
In Python, we have a module called
random, which helps us to generate random data. In this module there is a method called
random.random() which generates a number between 0 and 1 including 0 [0, 1). Let's first see the usage of the
Below is a simple code example where we have used the
## importing the random module import random ## prints a float between 0 and 1 print(random.random())
We can use the
ceil method of
math module to get an integer from the randomly generated floating value. It helps to pass it as an index to a list or string to make a random string.
We will have numbers from 0 to 9 stored in a
list. Then we will generate a random number using the
random() method and will add(concatenate) the corresponding indexed digit to a string. below we have the code for the same:
## importing modules import random import math ## storing strings in a list digits = [i for i in range(0, 10)] ## initializing a string random_str = "" ## we can generate any lenght of string we want for i in range(6): ## generating a random index ## if we multiply with 10 it will generate a number between 0 and 10 not including 10 ## multiply the random.random() with length of your base list or str index = math.floor(random.random() * 10) random_str += str(digits[index]) ## displaying the random string print(random_str)
Random string 809041
We can also generate different type of strings using the above procedure. If we want to generate a string which contains both digits and alphabets then, we can add all of those to a list and creates a random string of the desired length. Try it of your own. If you have any doubts, mention them in the comment section.
SHARE YOUR THOUGHTS WITH US!