To generate a random string of specified length in Python, you can use the random module, comprehension and the Python join() function.

import string
from random import randint

def random_char():
    alphabet = list(string.ascii_lowercase)
    return alphabet[randint(0,25)]

def random_string(n):
    return ''.join(random_char() for _ in range(n))

print(random_string(12))
print(random_string(12))
print(random_string(12))

#Output:
avfsqkkbydlx
xtpbkwjkvqzg
ymmmgdvjqmmr

The ability to randomly generate strings of random characters can be useful in different Python programs.

You can easily generate a random string of specific length in Python with the help of the random module.

First, you need to define the list of characters you want to select from. The Python string module has some great pre-defined constants which can be used to generate lists of characters.

For example, we can get a list of the lowercase letters of the alphabet with the pre-defined string constant ascii_lowercase.

There are also pre-defined constants for the uppercase characters, all characters lowercase and uppercase, and the digits 0 to 9 – to name a few.

After defining your list, you can then create a function which takes a number as an input. This number is the specified length.

With comprehension, we can loop for the specified number and get random characterrs from a helper function.

Finally, we can use the Python join() function to join all the characters together.

Below is a function which generates a random string given a length using Python.

import string
from random import randint

def random_char():
    alphabet = list(string.ascii_lowercase)
    return alphabet[randint(0,25)]

def random_string(n):
    return ''.join(random_char() for _ in range(n))

print(random_string(12))
print(random_string(12))
print(random_string(12))

#Output:
avfsqkkbydlx
xtpbkwjkvqzg
ymmmgdvjqmmr

If you want to use different character sets to generate the random character, you can adjust the selection list and use the choice() function.

import string
from random import choice

def random_char():
    chars = list(string.ascii_uppercase) + list(string.digits)
    return choice(chars)

def random_string(n):
    return ''.join(random_char() for _ in range(n))

print(random_string(12))
print(random_string(12))
print(random_string(12))

#Output:
5VSE2QISXTUC
WJJCNCEPJTU1
TDQPC62HXL78

Hopefully this article has been useful for you to learn how to use Python to generate a random string of specific length.

Categorized in:

Python,

Last Update: March 14, 2024

Tagged in: