DEV Community

Senuka Gunasekara
Senuka Gunasekara

Posted on

Python trick that generates a random password using the `secrets` module

a Python trick that generates a random password using the secrets module

import secrets
import string

def generate_password(length):
    characters = string.ascii_letters + string.digits + string.punctuation
    password = ''.join(secrets.choice(characters) for _ in range(length))
    return password

password = generate_password(12)
print(password)
Enter fullscreen mode Exit fullscreen mode

In this code snippet, we import the secrets module, which provides secure random number generation suitable for generating passwords. We also import the string module to access the various character sets available.

The generate_password function takes a parameter length to specify the desired length of the password. It creates a characters string by combining lowercase letters, uppercase letters, digits, and punctuation symbols. Then, it uses a loop and the secrets.choice function to randomly select characters from the characters string and concatenate them together to form the password.

Finally, we call the generate_password function with a length of 12 and print the generated password.


Hey see Me on GitHub

PythonPlumber (Senuka Gunasekara) · GitHub

I have no idea what I’m doing (╥ᆺ╥;). PythonPlumber has 7 repositories available. Follow their code on GitHub.

favicon github.com

Top comments (0)