×

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 TypeError

What is TypeError in python? TypeError is one of the exceptions in the python programming language. This exception occurs when an operation is performed on an unsupported object type or can...

6 minutes read.

Bar Plot in Python

A bar chart or bar graph displays categorical data using rectangular bars with heights or lengths proportionate to the values for the data distributed in the dataset. In a bar...

16 minutes read.

Python isinstance() function

Python isinstance() function The isinstance() function in Python returns a Boolean value ‘True’ if the given object is of the specified type, otherwise it returns False. Syntax isinstance(object, classinfo) Parameter object: It is a required parameter which represents an object. classinfo: This...

1 minute read.

Static Variables in Python

What is a Static Variable? The variable that remains with a constant value throughout the program or throughout the class is known as a " Static Variable ". Static variables are...

3 minutes read.

What is online python free IDE

An IDE is an acronym that stands for “Integrated development environment.” It is a software environment that has a software development package that consists of the code editor and builds...

4 minutes read.

Python String rfind() method

The string. rfind() method in Python returns the highest index in the string if the substring sub is found else it returns -1 if the substring is not found. Syntax string.rfind(sub [,start [,end]]) Parameter sub: This parameter...

2 minutes read.

Python Pass Statement

The pass statement is a null statement. The difference between pass and comment is that comment is ignored by the interpreter, whereas pass is not. The pass statement is typically used...

3 minutes read.

How to make API calls in Python

Information is extremely critical these days since it drives applications and organizations. It is subsequently critical to figure out how to get this information to serve your application. In fundamental...

4 minutes read.

Simple GUI calculator using PyQt5 in Python

GUI: The user is provided with information using manipulable visual widgets that don't require command-line input. These interface components respond to the user's interactions per the pre-programmed script, assisting each user's...

4 minutes read.

Python SQLite

SQLite It is an RDBMS (Relational Database Management System). It is an embedded, serverless, transactional SQL database engine. It is an open-source application. It is named SQLite because of its lightweight....

3 minutes read.

Python Key Error

What is an Error? Errors are nothing but problems in the program which occur in a program code, and this will stop the execution of the program. It is also called...

6 minutes read.

Socket Programming in Python

Socket Programming in Python In this tutorial, we will discuss network programming using Python programming language. We will explore all basic concept of network with Python script. Network Services in Python Python has...

9 minutes read.

Python Win32 Process

The Win32 process is essentially a Python procedure. This program provides access to advanced Win32 process creation and management features. Process objects are created through the Create method (the constructor)....

6 minutes read.

Python List reverse() method

 Python List reverse() method The list.reverse () method in Python reverses the elements of the list in place. Syntax list.reverse() Parameter NA Example 1 # Python program explaining # the list.reverse() method weekList = ['Sun','Thurs','Mon','Fri', 'Tues', 'Wed'] print("Actual week list: ",weekList) #...

1 minute read.

Isreal() Python

Python Programming Language Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It...

4 minutes read.

Python abs() function

Python abs() function The abs() function returns the absolute value of a number. Syntax abs(x) Parameter x: The parameter ‘x’ can be an integer value, a floating point number or a complex number. Return This function returns...

1 minute read.

How to build an Auto Clicker using Python?

What is an Auto Clicker? An Auto Clicker is software that is used for automating the click of a mouse on any particular element on the computer screen and controlling the...

8 minutes read.

Python Dictionary fromkeys() method

Python Dictionary fromkeys() method The dictionary.fromkeys() method in Python creates a new dictionary from the given sequence of elements and returns a dictionary with the specified keys and values. Syntax dictionary.fromkeys(sequence[, value]) Parameter sequence- This...

1 minute read.

Conditional Expressions in Python

In Python conditional expression are sometimes referred to operator called as ternary operator. Not only Python supports ternary operator but many other programming languages supports it. Ternary operator are the...

2 minutes read.

Python data science course

What is meant by Data Science? When processing raw, structured, and unstructured data utilizing various technologies, algorithms, and the scientific method, data science is a detailed study of the enormous quantity...

4 minutes read.