Python - Generate Random Password


Python - Generate Random Password

You can generate a random password from a desired set of characters.

To choose the character sets like alphabets, digits, or punctuation marks, we shall use string package.

To choose a random character from these character sets, we shall use random.choice() function.

And if we choose N number of times and join those characters, we end up with a randomly generated password of length N.

Examples

1. Generate password of specific length

In this example, we shall generate a password containing upper case alphabets, lower case alphabets, digits and punctuation mark characters.

We shall use string package to define allowed characters in our password.

Python Program

import random
import string

N = 20 #password length

#allowed string constants
allowedChars = string.ascii_letters + string.digits + string.punctuation

#genereate password
password = ''.join(random.choice(allowedChars) for _ in range(N))

print(password)

string.ascii_letters returns a string of lower and upper case alphabets.
string.digits returns a string of numbers from 0 to 9.
string.punctuation returns a string of symbols like !,@,#,$,[,], etc.

random.choice() picks a character randomly from these allowed characters we have taken.

Output

kfOJ4Vt$,-$[wBLB+q\'

Summary

In this tutorial of Python Examples, we learned how to randomly generate a password, with the help of well detailed examples.