DEV Community

Mario Python Plumber
Mario Python Plumber

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 (Mario Python Plumber) ยท GitHub

๐Ÿ“š๐Ÿ”ง Learning and building with Python, always seeking new ๐Ÿ”ฅ challenges and ๐Ÿ’ก opportunities to grow. A ๐Ÿ‘จโ€๐Ÿ’ป who โค๏ธ GNU/Linux ๐Ÿง lives in ๐Ÿ‡ฑ๐Ÿ‡ฐ! - PythonPlumber

favicon github.com

Top comments (0)