DEV Community

Angela
Angela

Posted on

Generate random passwords in Python using secrets

Read the docs: https://docs.python.org/3/library/secrets.html

I copied this example from python docs and added special characters to the password.

import secrets
import string


alphabet = string.ascii_letters + string.digits + '!@#$%^&*()-+[]'
while True:
    password = ''.join(secrets.choice(alphabet) for i in range(10))
    if (any(c.islower() for c in password)
            and any(c.isupper() for c in password)
            and any(c.isalnum() for c in password)
            and any(not(c.isalnum()) for c in password)
            and any(c.isdigit() for c in password)):
        break
Enter fullscreen mode Exit fullscreen mode

Top comments (0)