Generate Random String of Specific Length in Python

To generate a random string in Python starting with Python3.6, you can use the choices method from the Python's random module. The string module of Python allows us to quickly access some constants.


import string
import random

def generateRandomPassword(length):
    rand = "".join(random.choices(string.ascii_letters +
                                  string.digits + string.punctuation, k=length))
    return rand

rand_password = generateRandomPassword(10)
print("Randomly generated string is " + str(rand_password))
Output:
Randomly generated string is KJG%|D.us4

A random string can also be generated using secrets module of Python:


import string
import secrets

def generateRandomPassword(length):
    rand = "".join(secrets.choice(string.ascii_uppercase + string.digits)
               for x in range(length))
    return rand

rand_password = generateRandomPassword(10)
print("Randomly generated string is " + str(rand_password))
Output:
Randomly generated string is GS0K1U9HNN