AppDividend
Latest Code Tutorials

How to Generate Random String in Python

0

Random strings and numbers are useful when it comes to security. In computer science, predictable objects are less secure, and less predictable elements are more secure. When we are signing up for the services, we need to provide a password. We can use these random strings as a password, which is less predictable and more secure.

Python provides several packages that deal with a random string, numbers, and even cryptography.

Generate Random String in Python

To generate random string in Python, use the string module and random.choices() method.

The string module in Python contains different string constants, which include the ASCII characters of all cases. It also includes separate constants for uppercase, lowercase letters, digits, and special characters.

The random module in Python performs random generations.

Example

# app.py

import random
import string


def generate_random_string(length):
    letters = string.ascii_lowercase
    rand_string = ''.join(random.choice(letters) for i in range(length))
    print("Random string of length", length, "is:", rand_string)


generate_random_string(8)

Output

Random string of length 8 is: nwmqqxyf

In this example, we generate the random string based on the length we pass to the function.

Inside the function, we have generated a random string with the lowercase combination then use the string.ascii_letters constantThe string.ascii_letters constant includes all the lowercase and uppercase letters.

To generate the string with all the lowercase letters, then use the string.ascii_lowercase property.

In the next step, run a for loop n number of times, which is the length of the string to pick a single character from a string constant using the random.choice() method and attach it to the string variable and use the join() method to form a random string.

Let’s pass the 16 as a length, and it will generate the random string of length 16.

import random
import string


def generate_random_string(length):
    letters = string.ascii_lowercase
    rand_string = ''.join(random.choice(letters) for i in range(length))
    print("Random string of length", length, "is:", rand_string)


generate_random_string(16)

Output

Random string of length 16 is: oxepenikhgjmhknp

Generate random string with uppercase letters

To generate the string with all the uppercase letters, then use the string.ascii_uppercase property.

import random
import string


def generate_random_string(length):
    letters = string.ascii_uppercase
    rand_string = ''.join(random.choice(letters) for i in range(length))
    print("Random string of length", length, "is:", rand_string)


generate_random_string(16)

Output

Random string of length 16 is: MAWNYZRAVTHHGUVX

Each time you run the file, you will get a different output.

Generate a random string of specific letters only

You can generate a random string from specific letters only, instead of writing the string.ascii_uppercase, here you need to write the particular string from which you need to generate a random string.

Also, you don’t need a Python string module cause we are using a specific string.

import random


def generate_random_string(length):
    letters = 'bobbyelevenmilliehopperjane'
    rand_string = ''.join(random.choice(letters) for i in range(length))
    print("Random string of length", length, "is:", rand_string)


generate_random_string(16)

Output

Random string of length 16 is: leerljlbvmpelony

You can see that all the letters are taken from the provided letters.

Create a random string without repeated characters

The random.choice() function can take repeated characters, but the random.sample() method can’t pick up repeated characters, so that we can use the random.sample() method to generate a random string.

import random
import string


def generate_random_string(length):
    letters = string.ascii_lowercase
    rand_string = ''.join(random.sample(letters, length))
    print("Random string of length", length, "is:", rand_string)


generate_random_string(16)

Output

Random string of length 16 is: gvekicdsfmrxbuyj

Generate a random alphanumeric string in Python

To generate an alphanumeric random string in Python, use the string.ascii_letters and string.digits constants to get the combinations of letters and digits.

import random
import string


def generate_alphanum_random_string(length):
    letters_and_digits = string.ascii_letters + string.digits
    rand_string = ''.join(random.sample(letters_and_digits, length))
    print("Alphanum Random string of length", length, "is:", rand_string)


generate_alphanum_random_string(16)

Output

Alphanum Random string of length 16 is: n7b1K3wavxXrDdjO

You can see from the output that we got an alphanumeric random string.

Using secrets.choice()

Python provides a secrets package to generate cryptographically more secure random numbers. The secrets.choice() method has an internal algorithm that is framed in such a way that it generates less predictable random numbers.

import secrets
import string


def generate_alphanum_crypt_string(length):
    letters_and_digits = string.ascii_letters + string.digits
    crypt_rand_string = ''.join(secrets.choice(
        letters_and_digits) for i in range(length))
    print("Cryptic Random string of length", length, "is:", crypt_rand_string)


generate_alphanum_crypt_string(16)

Output

Cryptic Random string of length 16 is: Pq9hga3IyExXKVhX

Conclusion

If you are generating a secure password then my suggestion would be to use secrets.choice() method instead of random.choice() method. That is it for this tutorial.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.