×

Python Program to Generate a Random String

The term "random" refers to a group of information or data that can be accessed in any chronological order. To create random strings, a Python program called random is utilized. The punctuation, characters, and numbers that make up the random string might all have different patterns. To create a secure string, the random module has two methods: random.choice() and secrets.choice(). Let's examine the secrets.choice() and random.choice() methods in Python to create a random string.

Using random.choice()

The python string generates a series of letters and numbers that really can repeat the string in any position using the random.choice() function.

Make a program that utilizes the random.choices() function to produce random strings.

import string    
# The random module is defined here
import random   
# The string's character number.
Str = 10   
# In order to determine the string in Uppercase + Numeric data, call the random.choices() string module.
rand = ''.join(random.choices(string.ascii_uppercase + string.digits, k = Str))  
# The random data to be printed.  
print("The randomly generated string is: " + str(rand)) 

Output:

The randomly generated string is: EHNXLB8LDU

The steps utilized to create the random string in the random module are listed below.

FunctionsDescription
String.punctuationIt generates a string at random and includes punctuation in the string.
String.digitsIt generates a string at random and returns one with numerical characters.
String.ascii_lowercaseIt's a random string technique that only outputs lowercase characters in the string.
String_ascii_uppercaseIt is an uppercase-only random string technique that only produces uppercase strings.
String.ascii_lettersIt produces a random string with both capital and lowercase letters.

Create an Arbitrary String of Capital and Lowercase Letters

# Create a program that will produce the random string in both upper- and lowercase.
import random  
import string  
# Create the function and input the argument length.
def Upper_Lower_string(len): 


# Continue looping till the specified length
    rslt = ''.join((random.choice(string.ascii_lowercase) for x in range(len))) 
# Print in lowercase for the string.
print(" Random string generated in Lowercase: ", rslt)  
# Repeat until the defined length is reached.
rslt_1 = ''.join((random.choice(string.ascii_uppercase) for x inrange(len))) 
    # Print in uppercase for the string.  
print(" Random string generated in Uppercase: ", rslt_1)  
# Define the length  
Upper_Lower_string(10) 

Output:

Random string generated in Lowercase:  beubaotodx
Random string generated in Uppercase:  SPTZVKDMMY

A Specified Random String of Characters

# Make a program that will generate the provided random letter string.
import random  
import string  
def specific__string(len):  
# Specify the particular string
sample__string = 'pqrstuvwxy' 
    # Specify the conditions for a random string.
    rslt = ''.join((random.choice(sample__string)) for x in range(len))  
    print(" The randomly generated string is: ", rslt)  
# Define the length  
specific__string(6) 
specific__string(11)  

Output:

The randomly generated string is:  qqspsp
The randomly generated string is:  qvtpqpsuupw

Note: The same character strings are repeated in the Python application using the random.choice() method. Use the random.sample() function to prevent repeating character displays.

Make a random string and avoid using the same characters more than once

import random  
import string  
print ("Use of random.choice() function")  
def specific__string(len):  
     # Declare the string in lower case.
    letter = string.ascii_lowercase
     # define the condition for random.choice() method  
rslt = ''.join((random.choice (letter)) for x in range(len))  
    print (" Random generated string with repetition: ", rslt)  
# Define the length    
specific__string(8) 
specific__string(10)  


# Print the space  
print ("") 
print ("Use of random.sample () function")  
def WithoutRepeat(len):  
# Define the specific string  
    letter = string.ascii_lowercase
    # Set the conditions for the random.sample() function.
    rslt_1 = ''.join ((random.sample (letter, len)))   
    print (" Random generated string without repetition: ", rslt_1)  
  # define the length  
WithoutRepeat(6) 
WithoutRepeat(11) 

Output:

Use of random.choice() function
 Random generated string with repetition:  ubqjxbhf
 Random generated string with repetition:  zvmzllmmno


Use of random.sample () function
 Random generated string without repetition:  umrzhq
 Random generated string without repetition:  djcgspxfoyn

The random.sample() method produces a string in which every character is distinct and non-repeating, as we can see in the output above. The random.choice() method, however, produces a string that can include repeating characters. Therefore, we can assert that using the random.sample() function will provide a unique random string.

Make an alphanumeric string at random with fixed letters and digits

For instance, let's say we need an alphanumeric string that is generated at random and has 5 letters and 4 digits. These parameters must be defined in the function.

Let's create software that will produce an alphanumeric string with a predetermined amount of letters and digits.

Code:

import random  
import string  
def random__string(letter__count, digit__count):  
    str_1 = ''.join((random.choice(string.ascii_letters) for x in range(letter__count)))  
    str_1 += ''.join((random.choice(string.digits) for x in range(digit__count)))  
#It transforms the string into a list.
    sam__list = list(str_1) 
# The string is shuffled using the random.shuffle() function.
    random.shuffle(sam__list) 
    final__string = ''.join(sam__list)  
    return final__string  


# Specify the letter to be nine characters long and the numbers to be five.
print ("Generated random string of the first string is:", random__string(9, 5))  


# Specify the letter to be six characters long and the numbers to be four.
print ("Generated random string of the second string is:", random__string(6, 4))  

Output:

Generated random string of the first string is: 72iFX6e0BPot5X
Generated random string of the second string is: rw6E4UYx05

Using secrets.choice()

To create a random string that is more secure than random.choice(), use the secrets.choice() method. Using the secrets.choice() method, is a cryptographically random text generator that makes sure no two processes may get the same results at the same time.

Let's create code that uses the secrets.choice() method to print a safe random string.

import string 
# Import package   
import secrets 
# Declare the string’s length 
n = 11
# Specify the string.ascii letters + string.digits parameters for the secrets.choice() function.
rslt = ''.join(secrets.choice(string.ascii_letters + string.digits) for x in range(n))  


# Print the Secure string   
print ("The safe random string is:"+ str(rslt))  

Output:

The safe random string is:kks2CNffn82

To create a secure random string, use the random module's alternative technique.

Let's create a program that prints secure random strings with several secrets.choice() techniques.

Code:

# Create a program that employs the secrets.choice() to display various random string methods.
import random   
import string  
import secrets 
# Declare the string’s length   
n = 11
# Create the secrets.choice() function and supply the arguments string.ascii letters + string.digits.
rslt = ''.join(secrets.choice(string.ascii_letters + string.digits) for x in range(n))  
# Print the Safe string using an ascii letter and digit combination.
print ("The safe random string is:"+ str(rslt))  


rslt = ''.join(secrets.choice(string.ascii_letters) for x in range(n))  
# Print the safe string using the specified ascii characters.
print ("The safe random string is:"+ str(rslt))  


rslt = ''.join(secrets.choice(string.ascii_uppercase) for x in range(n))  
# Print the Safe string in capital letters.
print("The safe random string is: "+ str(rslt))  


rslt = ''.join(secrets.choice(string.ascii_lowercase) for x in range(n))  
# Print the Safe string in small letters.
print ("The safe random string is:"+ str(rslt))  


rslt = ''.join(secrets.choice(string.ascii_letters + string.punctuation) for x in range(n))  
# Print the Safe string using the appropriate characters, including punctuation.
print ("The safe random string is:"+ str(rslt))  


rslt = ''.join(secrets.choice(string.digits) for x in range(n))  
# Using string.digits, print the safe string.
print ("The safe random string is:"+ str(rslt))  


rslt = ''.join(secrets.choice(string.ascii_letters + string.digits + string.punctuation) for x in range(n))  
# Print the Safe string with the combination of characters, including letters, numbers, and punctuation.
print ("The safe random string is:"+ str(rslt))  

Output:

The safe random string is:5ITtugYqSm8
The safe random string is:YaNQBbBlEWE
The safe random string is:VMSYCRVEIRI
The safe random string is:wamafhwmgwb
The safe random string is:X_.-TTQbW#\
The safe random string is:83960935735
The safe random string is:NKOkS:4BTfy

Related Topics

Python String isspace() method

Python String isspace() method The string.isspace() method returns a Boolean value true if there are only whitespace characters in the given string. This function is used to check if the given...

2 minutes read.

Python Write Excel File

Python Write Excel File The Python xlwt module is used to write an excel file and perform multiple operations on it. It can be used to write text, numbers, and formulas for multiple...

3 minutes read.

Salary of Python Developers in India

In this tutorial, we will understand who python developers are and what is their salary when they work in India. Python Developers Python Developers are the people who are involved in designing...

4 minutes read.

Python List sort() method

The list.sort () method in Python sorts the items of the list in place. Syntax list.sort(key=None, reverse=False) Parameter reverse: If a Boolean value ‘True’ is passed, the  sorting will be done in the descending order else for ‘False’...

2 minutes read.

What are the Purposes of Python?

Python is a high-level programming language that is simple to use and easy to write, and Python is a beginner-friendly programming language. A beginner often prefers to start with Python...

6 minutes read.

Python Stack

Python Stack: The work Stack is defined as arranging a pile of objects or items on top of another. It is the same method of allocating memory in the stack...

10 minutes read.

How to plot a Histogram in Python

A Histogram is used to represent a given data provided as a chunk. This histogram is a graphical representation that uses bars to indicate the ranges of the data. In...

4 minutes read.

Python Data Visualization

In this tutorial, we will understand what data visualization means in python. Further, we will see different methods of visualizing data in python. Data visualization In a non-technical language, it is a...

4 minutes read.

Python bytearray()

Python bytearray() Class The bytearray() class is used to return a bytearray object which is an array of the specified bytes. It gives a mutable sequence of integers in the range 0...

1 minute read.

Python Modules List

Python is like an ocean. If you have been working with Python, you might’ve already heard the word module. When we solve a problem in mathematics, there will be several...

3 minutes read.

Python format() function

Python format() function The format() function in Python formats a specified value into the given format. A ‘TypeErrorexception’ is raised if the method search reaches the object and the format_spec is non-empty, or if either the format_spec or the...

1 minute read.

Difference between Python 2 and Python 3

In this tutorial, we will learn the differences between two versions of python, that is, python version 2 and python version 3. Some basic differences include- Python 2 is the older version...

3 minutes read.

Palindrome program in Python

Palindrome program in python A number or string is said to be a palindrome if we invert the number or string and the string or number remains the same as the...

3 minutes read.

Python program to find Fibonacci series

Python program to find Fibonacci series A Fibonacci series is an integer sequence of 0, 1, 1, 2, 3, 5, 8.... We can identify the Fibonacci series as any number sequence...

2 minutes read.

Cross Entropy in Python

Introduction Cross-entropy loss is frequently combined with the softmax function. Determine the total entropy among the distributions or the cross-entropy, which is the difference between two probability distributions. For the purpose...

5 minutes read.

List Comprehension in Python

Sometimes we need new lists that are completely based on previously existing lists, so to perform this operation successfully, some of the programming languages come with a syntactic construct known...

5 minutes read.

List in Python

What is List in Python In Python, lists are used to store the multiple values in one variable. We can say that list is the collection of similar as well as...

3 minutes read.

Python Knapsack problem

Python Knapsack problem Before we dig down about Knapsack problems in Python, first let's have a look at what is actually a knapsack problem. What is a knapsack problem? A problem from the...

5 minutes read.

How to Concat two Dataframes in Python

Using Pandas dataframe, we can concat two dataframes or series in Python. So let's take a brief introduction to what is Pandas in Python. Pandas is a library typically used for...

7 minutes read.

How to Fix an EOF Error in Python?

Introduction An EOF (End-of-File) error occurs when a program tries to read beyond the end of a file or a stream, causing it to return an error message. It can happen...

8 minutes read.