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)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay