Random Number String Generation in Python
This Tutorial is about to generate random string in Python using Random Module. Python contains a lot of Predefined modules. Python has a module that is the random module that can be used to generate random number string using its various methods.
The random is one of the Modules to get the data by the system itself based on the system logic. Random Module is basically used in the One Time Password (OTP) generation, and in some Games to choose some random Decisions.
Importing random Module
Random Module can be imported as follows:
We can also import all the methods present in random module by
from random import *
Or else we can also import specific methods from a module like randint from random Module like as follows:
from random import randint #Here it imports only randint method among all the Other Methods
Usage of Randint Method:
- start is the starting Position of the generations of Random Numbers
- end is the last but one Position of the generations of Random Numbers
- random.randint(0,10) #Generates a Random Number from 0 to 10
- random.randint(10) #Generates the same i.e. no need to mention the start position i.e. default=0
Python program to Generate Random number string
Look at the following code for usage of randint method:
from random import randint ri = randint(11111,99999) numstr = str(ri) print(numstr)
The above program will give the output of a random number as a string which will be between 11111 and 99999.
First, we have used the randint() method to get the random integer. After that, we have used the str() method to convert our integer into a string. Thus, we are able to generate a random number string in Python.
Using for loop with random module
Now see a program to generate the string of random numbers:
from random import randint s="" k=int(input()) for i in range(0,k): s=s+str(randint(0,k)) print("Random Number String is",s)
Below is the output of the above program:
Random Number String is 03103
From the Above Code,
- s is the String that stores the Random Numbers generated by randint method.
- k is an integer which specifies the Ending Position to the randint method
Finally, in order to get a series of random numbers we’ve used a for loop and displayed the total String s.
The above consider an input range for random number generation boundary based on the boundary taken an empty string whatever the random number is obtain the type converted to a string and concatenated to the variable “s” and display the output
Here’s a Tutorial to create a List of Random Numbers Click Here->List of Random Numbers
For further Reference on Random Module Click Here ->Random Module -PyDocs