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)