×

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

Spyder (32-bit) - Free download

Spyder is a free and open-source scientific environment created by and for Python engineers, scientists, and data analysts. It is a robust scientific environment created in Python by and for...

3 minutes read.

Python Virtual Environment

In this tutorial, we will understand Virtual Environment in Python. We will understand the need for a virtual environment and also see how to make use of it in python....

3 minutes read.

Reading a File Line by Line in Python

Introduction In this tutorial, we will learn about reading files in python line by line. Before reading the files, let us know a little information about the files first. Files A file is...

6 minutes read.

Convert uppercase to lowercase in Python

Python String lower() By using the built-in string lower() method, all the uppercase characters can be converted into lowercase characters in a string, The lowercased string from the given string is returned...

1 minute read.

Python Set issuperset() method

Python Set issuperset() method The set.issuperset() method in Python returns a boolean value True if all items in the specified set exists in the original set, else it returns False. Syntax set.issuperset (set1) Parameter set- This parameter represents the...

2 minutes read.

Python Comment Block

In this tutorial, we will see what comment blocks mean in Python. Further, we will see the commenting methods supported in Python. We will understand the topics deeply with the...

6 minutes read.

Python And Operator

Python's and operator takes two operands that can be either object, Boolean expressions, or both. And operator creates more complex expressions using those operands. Conditions are the common name for...

8 minutes read.

Python for Loop Increment

Introduction In general, loops are employed for sequential traversal. It belongs to the definite iteration category. Definite iterations imply that the number of iterations is explicitly set in advance.  In this article,...

4 minutes read.

Python Graph

Python Graph: In Computer Science and Mathematics, a Graph is a pictorial representation of a group of objects or elements where some elements are connected using the links. A graph...

5 minutes read.

Hog Descriptor Opencv Python

Python programming language: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a...

3 minutes read.

Add a key-value pair to dictionary in Python

In programming, data type defines the type of value that a variable can hold. With help of these, we can perform various mathematical, logical, or relational operations on that particular...

5 minutes read.

How To Install Python In Ubuntu

How To Install Python In Ubuntu Ubuntu is free and open-source software and it is an essential part of the Linux distribution. It is a popular operating system developed by Canonical. If we...

3 minutes read.

Python Tuple count() Method

Python Tuple count() Method The tuple.count() method in Python returns the number of times a specified value appears in the tuple. Syntax tuple.count(value) Parameter value- This parameter represents the element to search in the tuple Return This...

1 minute read.

Python pow() Function

Python pow() Function The pow() function in Python return the parameter ‘x’ to the power ‘y’ and if the parameter ‘z’ is present, it returns x to the power y, modulo z (computed more efficiently than pow(x, y) % z). Syntax pow(x, y[, z]) Parameter x: This parameter represents the base...

1 minute read.

Not supported between instances of str and int in python

In this article, you are going to learn why the type error occurs between instances of string and integer datatypes. Also, you will know what kind of error is the...

6 minutes read.

Compound Interest GUI Calculator using Tkinter in Python

GUI: One of the most significant factors that increased the usability of computer and digital technologies for common, less tech-savvy users is likely the development and widespread adoption of GUIs. GUIs...

6 minutes read.

Python String Variable

Python programming language: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a...

4 minutes read.

Math Module in Python

In this article, you are going to learn everything in detail about the “ math “ module in Python. We can normally work with general operations using python without importing or...

16 minutes read.

Python program for perfect number

Python program for perfect number Before writing any program for a given problem, we have to understand the problem for which we are creating a solution program. So, let's understand what...

2 minutes read.

Python JSON Schema

Python-jsonschema JSON: JSON stands for JavaScript Object Notation. It is a text-based format that represents structured data and can be used to interchange data among various applications. This is self-defining language...

5 minutes read.