Generate Random String in Python

  • Post category:String

To generate random string in Python, we will use the random() module. To randomly select a character from a list of potential characters random.choice() is used. This function takes a list of characters as an argument and randomly selects a single character from that list.

Thus, we have the ability to join these characters into a single string.

Step 1: Import the necessary modules

import random
import string

Step 2: Generate a random string of fixed length

def randomString(stringLength=10):    
    letters = string.ascii_lowercase
    return ''.join(random.choice(letters) for i in range(stringLength))

print("Random String is:", randomString())

Output:

Random String is: xicrkeumpp

Tip: You can use string.ascii_letters, string.digits, and string.punctuation to generate a random string of different formats.

Free resources to learn advanced skills: AiHints and CodeAllow