In this article let's learn how to generate a random string using the Python program. given a string size as an input to the Python program your task is to generate a random string and display it to the user.
Let use random module to generate the random strings
Write a Python Program to Generate a Random String
import the required module string and random module that the program requires. Using the input function call, ask a user to enter an integer. The integer is the size of the string that we have to generate. Store the integer variable name as size
We required a string module to get the English lower case alphabets and a random module to generate random English alphabets.
import string
import random
size = int(input("Enter string Size to Generate : "))
Let's take another variable text and using a random choice function call pass the string lowercase letters and space and value of integer size to the choice function.
random.choice() is a function that will select the character randomly, returns the list of characters and once the choice function returns convert the list to string using join function call as shown below
text = "".join(random.choices(string.ascii_lowercase + " ", k=size))
Once the random string is generated and stored in variable text use the print function call to print the random generated string National below
print("The Random String Generated is : ", text)
Python Complete Code
================================
import string
import random
size = int(input("Enter string Size to Generate : "))
text = "".join(random.choices(string.ascii_lowercase + " ", k=size))
print("The Random String Generated is : ", text)
OUTPUT
==================
Enter string Size to Generate : 200
The Random String Generated is : udyvwkueovqnnoedfdlzngveuuwedexldeggcoymfndvyrabmnoxgnqa llzlyhyzxmcqwqjhfupovxskmcrzirmyhmetgmvjwuscdbzuudwwblzgrgzitlqtefoilvueznvgip mraadgatjvouwruw nxinhsnv cfwqmckpghgyckxvaxjjhmbt jrohntrcq xws
OUTPUT 2
===================
Enter string Size to Generate : 30
The Random String Generated is : qvuzsstxuygkwqsudosuokzpvdayys
OUTPUT 3
==================
Enter string Size to Generate : 12
The Random String Generated is : ltocaz wufdx
Conclusion
=================
Execute the above program by providing the random value of size of a string and note down the result.
Comment down below if you have any suggestions to improve the above program
0 Comments