python

Python program to Generate a Random String

In Python, it is often useful to generate random strings for various purposes, such as generating unique IDs, passwords, or test data. Python provides several modules that allow you to generate random strings easily.

Python program to Generate a Random String

To generate a random string in Python, you can use the random module and the string module.

Here is an example of how to generate a random string of length 10, containing only lowercase letters:

import random
import string

def generate_random_string(length):
    return ''.join(random.choices(string.ascii_lowercase, k=length))

random_string = generate_random_string(10)
print(random_string)

Output

brwfdtgehv

In this example, the random.choices() function is used to choose 10 random lowercase letters from the string string.ascii_lowercase, which contains all the lowercase letters in the ASCII character set. The join() function is then used to join the randomly chosen letters into a single string.


You can modify the above code to generate random strings of other lengths or containing other characters. For example, you can use string.ascii_uppercase to generate a string containing only uppercase letters, or string.digits to generate a string containing only digits. You can also combine these character sets to generate strings containing a mixture of different characters.

import random
import string

def generate_random_string(length):
    characters = string.ascii_lowercase + string.ascii_uppercase + string.digits
    return ''.join(random.choices(characters, k=length))

random_string = generate_random_string(10)
print(random_string)

Output

yXcUohXpVv

Note that the random strings generated using this method are not truly random, as they are generated using a pseudo-random number generator. If you need to generate truly random strings, you can use a hardware random number generator or a secure random number generator provided by the secrets module.

Was this helpful?