How to Generate a random string of a given length in Python?

In Python, Generating a random string is pretty straightforward. However, there are scenarios where we need to generate a random string that includes alphanumeric characters for a strong password.

There are various approaches to achieve this functionality.

Generate a random Mixed case alphabet string

If you want to generate a mixed case alphabet random string, then you string.ascii_letters and random.choice() for a given specified length as shown below.

import random
import string

def generateRandomString(length):
    # Generate mixed case alphabets string
    letters = string.ascii_letters
    result_str = ''.join(random.choice(letters) for i in range(length))
    print("Random string of length", length, "is:", result_str)


generateRandomString(8)

# Output
# Random string of length 8 is: hNIgRMoC

Generate a random Upper case alphabet string

If you want to generate a random upper case alphabet string, then you string.ascii_uppercase and random.choice() for a given specified length as shown below.

import random
import string


def generateRandomUpperCaseString(length):
    # Generate upper case alphabets string
    letters = string.ascii_uppercase
    result_str = ''.join(random.choice(letters) for i in range(length))
    print("Random upper case string of length", length, "is:", result_str)


generateRandomUpperCaseString(10)

# Output
# Random upper case string of length 10 is: FXFUJHAUOJ      

Generate a random Lower case alphabet string

If you want to generate a random lower case alphabet string, then you string.ascii_lowercase and random.choice() for a given specified length as shown below.

import random
import string

def generateRandomLowerCaseString(length):
    # Generate lower case alphabets string
    letters = string.ascii_lowercase
    result_str = ''.join(random.choice(letters) for i in range(length))
    print("Random lower case string of length", length, "is:", result_str)

generateRandomLowerCaseString(10)

# Output
# Random lower case string of length 10 is: rtssovidqa         

Generate a random Alphanumeric string

If you want to generate a random alphanumeric string, then you string.ascii_lowercase + string.digits and random.choice() for a given specified length as shown below.

import random
import string

def generateRandomAlphaNumericString(length):
    # Generate alphanumeric string
    letters = string.ascii_lowercase + string.digits
    result_str = ''.join(random.choice(letters) for i in range(length))
    print("Random alphanumeric string of length", length, "is:", result_str)


generateRandomAlphaNumericString(12)

# Output
# Random alphanumeric string of length 12 is: ae8nd6149q7j         

Generate a random strong password using string module

If you want to generate a strong password using the string module, then you string.ascii_letters + string.digits + string.punctuation and random.choice() for a given specified length as shown below.

import random
import string

def generateRandomStrongPassword(length):
    # Generate random strong password
    letters = string.ascii_letters + string.digits + string.punctuation
    result_str = ''.join(random.choice(letters) for i in range(length))
    print("Strong Password of length", length, "is:", result_str)


generateRandomStrongPassword(12)

# Output
# Strong Password of length 12 is: Au}h]D=aJ~QN 

Note– random.choice() can repeat the characters. If you don’t want to repeat the characters, then use random.sample() method. 

Generate a random strong password using the secrets module

If you are looking for a secure and robust password, Python has a module called as secrets, and you could utilize this to generate a random secured password. The algorithm used by secrets is less predictable when compared to the random string module generation.

import secrets
import string

def generateRandomCryptoPassword(length):
    # Generate random password using cryptographic way
    letters = string.ascii_lowercase + string.digits + string.punctuation
    result_str = ''.join(secrets.choice(letters) for i in range(length))
    print("Strong Password using Crpyto of length", length, "is:", result_str)


generateRandomCryptoPassword(12)

# Output
# Strong Password using Crpyto of length 12 is: ^6cg1(d^o/~(

Note: This module works perfectly with Python 3.6 and above.

1 comment
Leave a Reply

Your email address will not be published.

Sign Up for Our Newsletters

Get notified of the best deals on our WordPress themes.

You May Also Like
Importerror No Module Named Pandas

ImportError: No module named Pandas

In Python, if you try to import pandas without installing the module using pip, you will get ImportError: no module named pandas error.  In this tutorial, let’s look at installing…
View Post
Typeerror Unhashable Type 'List'

TypeError: unhashable type: ‘list’

Table of Contents Hide TypeError: unhashable type: ‘list’Example – unhashable type: ‘list’Solution to TypeError: unhashable type: ‘list’.Solution 1 – By Converting list into a tupleSolution 2 – By Adding list…
View Post