How to Generate Random Strings and Passwords in Python?

Posted in

How to Generate Random Strings and Passwords in Python?
vinaykhatri

Vinay Khatri
Last updated on October 31, 2024

    To generate random data in Python, we generally use Python's random module.  And in this tutorial, you will learn how to use the Python random module to create random strings and passwords.

    How to create a random string in Python?

    To generate a random string of any length, we can use the Python random module. Here are the steps to create a random string in Python.

    Step 1: Import the string and random modules

    import string
    import random

    The string module has different string constant values for all ASCII characters, which include uppercase & lowercase alphabets, digits, and special characters or symbols. We will use the string module as a database to get the random characters.

    With the random module methods, we can pick the random characters from the string module to generate random string values.

    Step 2: Create a string value of lowercase letters

    After importing the modules to the script, we need to create an identifier of all the letters, either lowercase or uppercase, from which we will pick the random characters.

    lowercase_letters = string.ascii_lowercase   #'abcdefghijklmnopqrstuvwxyz'
    
    

    Step 3: The length of the random string and an empty random string.

    Store the length of the random string as a size identifier. And also, initialize an empty string that will store the random letters for the random string.

    size = 8
    random_string = ""

    Step 4: Run a loop from range 0 to size

    Now we need to run a loop for the total size of the random string. And with each iteration, we will pick a random number from lowercase_letters using the random.choice() function and add it to the random_string .

    for i in range(size):
        #pick a random letter
        letter = random.choice(lowercase_letters)
        
        # add the random letter to random_string
        random_string += letter

    Example

    Let's put all the steps together and generate a long Python random string.

    import string
    import random
    
    lowercase_letters = string.ascii_lowercase   #'abcdefghijklmnopqrstuvwxyz'
    
    size = 8
    random_string = ""
    
    for i in range(size):
        #pick a random letter
        letter = random.choice(lowercase_letters)
        
        # add the random letter to random_string
        random_string += letter
    
    print("Your Random String is: ", random_string)
    

    Output

    Your Random String is: ztaoelsf

    In the above example, we only pick the random characters from the lowercase alphabets. We can also use a different set of characters such as uppercase, digits, or special characters. The string module provides different properties for various ASCII characters.

    String Properties Description Return Value
    string.ascii_lowercase It returns a string of all lowercase letters. 'abcdefghijklmnopqrstuvwxyz'
    string.ascii_uppercase It returns a string of all uppercase letters. 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
    string.ascii_letters It returns a string of all upper and lower case letters. 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
    string.digits It returns a string of numbers from 0 to 9 '0123456789'
    string.punctuations It returns a string of punctuations or special characters. '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
    string.whitespace It return a string of escape characters such as tab, linefeed, new line etc. ' \t\n\r\x0b\x0c'
    string.printable It returns a string of all characters that are printable string values. '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c'

    Create a Random String of Lower and Upper case letters

    In the above example, we see how we can generate a random string of lowercase letters. Now let's write a Python program that can generate a random string containing upper case and lowercase letters.

    To pick the random lowercase and uppercase letters, we can either use the string concatenation of string.ascii_lowercases+string.ascii_uppercases or string.ascii_letters .

    Example

    import string
    import random
    
    letters = string.ascii_letters  
    size = 8
    random_string = ""
    
    for i in range(size):
        #pick a random letter
        letter = random.choice(letters)
        
        # add the random letter to random_string
        random_string += letter
    
    print("Your Random String is: ", random_string)
    

    Output

    Your Random String is: pwVWSmQE

    Create a Random String of  specific letters letters

    To create a random string from a specific set of letters, we first need to specify all the specific letters as a single string. And with random.choice() function, we can pick random letters from it.

    Example

    import string
    import random
    
    #specific letters
    letters = "TECHGEEKtechgeek"
    size = 8
    random_string = ""
    
    for i in range(size):
        #pick a random letter
        letter = random.choice(letters)
        
        # add the random letter to random_string
        random_string += letter
    
    print("Your Random String is: ", random_string)
    

    Output

    Your Random String is: ehEHCHkE

    Generate Random String without Repeating letters

    While creating a random string using Python, there is a high chance that the random string may contain repetitive characters. This is because of the random.choice() function picks random characters from the source string. To pick only unique characters, we can use the random.sample() function.

    The random.sample(sequence, k) function accepts two arguments sequence and k , and it returns a list of k unique random items or characters from the sequence. In the case of a string, it will return a list of random k numbers of characters from the string.

    Example

    import string
    import random
    
    #specific letters
    letters = string.ascii_letters
    size = 8
    
    #generate a random unique chracters string
    random_string = "".join(random.sample(letters, k=size))
    
    print("Your Random String is: ", random_string)

    Output

    Your Random String is: fzrDgqOt
    

    How to create a Random Password with letters, special characters, and digits?

    Suppose you need to write a script that generates random strong passwords, which can include letters, special characters, or digits. How would you do that?

    For creating such a random password generator in Python, we can use the combination of string.ascii_letters , string.digits , and string.punctuation for the string source and random.choice() function to pick random letters, digits, and special characters.

    Example 1: Create a random password in Python

    import string
    import random
    
    #all characters
    characters =  string.ascii_letters + string.digits + string.punctuation
    
    #size of the password
    size = 10
    
    #generate a random password using Python
    random_password = ""
    
    for i in range(size):
        #pick a random character from characters
        character = random.choice(characters)
    
        #add the random pick character to the random password
        random_password += character
    
    print("Your Random password is:",random_password)
    

    Output

    Your Random password is: kf}3%0YbK5

    Example 2: Create a random password of unique characters in Python

    There is a chance that the above random password generator example might create a password of all same characters. To create a password with all random unique characters we can use the random.sample() function instead of random.choice().

    import string
    import random
    
    #all characters
    characters = string.ascii_letters + string.digits + string.punctuation
    
    #size of the password
    size = 10
    
    #generate a random strong password using python
    random_password= "".join(random.sample(characters, k=size))
    
    print("Your Random Unique characters password is: ", random_password)

    Output

    Your Random Unique characters password is: fSRl$(Es96

    Random Passwords with fixed numbers of letters, digits, and symbol

    Let's say you need to generate a random strong password that must contain at least one uppercase letter, one lowercase letter, one digit, and one special character. The above two password generator programs may give us strong and unique passwords, but still, there is a chance that they might not include all the characters. It might also be possible they only create a random unique password of all lowercase letters, or digits, or special characters.

    If you want to generate a password that must include at least one of all the characters, we have to specify the count for all the characters group, pick the random character from them and add them to create a single strong password.

    Example

    import string
    import random
    
    #function to generate password
    def generate_password(upper_count=1, lower_count=1, digits_count=1, special_count=1):
        
        random_upper = "".join(random.sample(string.ascii_lowercase, k=upper_count))
        random_lower = "".join(random.sample(string.ascii_uppercase, k=lower_count))
        random_digits = "".join(random.sample(string.digits, k=digits_count))
        random_special = "".join(random.sample(string.punctuation, k= special_count))
    
        #add all the random chracters to form a password
        random_password = random_upper+random_lower+random_digits+random_special
    
        print(f"Your {len(random_password)} characters long Random Password is: ", random_password)
    
    #upper_count >= 26
    upper_count = 3 # 3 uppercase characters
    
    #lower_count >=26
    lower_count = 5  #5 lowercase characters
    
    #digits_count >=10
    digit_count = 4    # 4 digits
    
    #special_count >=32
    special_count = 4  #4 special characters  
        
    generate_password(upper_count,lower_count, digit_count,special_count)
    

    Output

    Your 16 characters long Random Password is: ijsHPZRL4290*$[/

    How to generate secure random string tokens in Python?

    While dealing with APIs, we are often required to generate random secure tokens for various purposes, such as authentication and secure communication gateways. Python comes with inbuilt secrets modules for such tasks, which can generate cryptographically strong random numbers, passwords, and security tokens.

    Example 1:

    Let's create a 16 bytes hexadecimal random string token using the Python secrets library and token_hex(nbytes) module.

    import secrets
    
    print("Your 16 bytes hexadecimal string token is:", secrets.token_hex(16))

    Output

    Your 16 bytes hexadecimal string token is: a25f48a34a6bf77f5120dfc32d0581b4
    

    Example 2

    To create a URL friendly secure token we can use the secrets' token_urlsafe(nbytes) method.

    import secrets
    
    print("Your 16 bytes url safe string token is:", secrets.token_urlsafe(16)

    Output

    Your 16 bytes url safe string token is: gX0OllOPGgTSDmYZ7aMwHA
    

    How to generate a secure random UUID in Python?

    Most of the high-end applications provide a secure random UUID to every user for unique identification. In the backend database more than integer ID, UUID is used as a primary key. Python has a standard library UUID, that provides a uuid4() method to generate random UUID's.

    Example

    Let's generate a random UUID using Python

    import uuid
    
    print("Your secure UUID is", uuid.uuid4())

    Output

    Your secure UUID is 695aff53-d77f-4c79-9add-0cade070288f

    Conclusion

    Generate random strings, and numbers often asked during Python interviews. There are many ways to generate a random string in Python, and in this article, we have only discussed the most common and efficient ones. For a more real-world approach, we also discussed how we could generate random and unique passwords, tokens, and UUID using Python and its different libraries.

    If we have missed any approach, or you want to share your thoughts and code with us. Please write your's comments in the comment section.

    People are also reading:

    Leave a Comment on this Post

    0 Comments