How to Generate Random Passwords in Python

This tutorial will show you how to generate random passwords in Python.

 

The first step is to build a list of possible characters to choose from. We can get different sets of ASCII characters from the string package. Here are the ones useful for creating passwords:

 

  • ascii_lowercase – All lowercase letters in the English alphabet.
  • ascii_uppercase – All lowercase letters in the English alphabet.
  • ascii_letters - All lowercase and uppercase letters in the English alphabet.
  • digits – numbers 0-9.
  • punctuation – All special characters such as *!{} .etc.
  • whitespace – All whitespace characters.
  • printable – All printable ASCII characters (all the above combined).

 

Python Password Generation Example

To make a password we need to pick characters at random from a string of characters provided by the string package. This is done using the choice function from the random package. We will iterate over this function to get the desired number of characters for the password and add them to a new string using the Python .join() function.

 

import string
import random

length = 6
chars = string.ascii_lowercase

res = ''.join(random.choice(chars) for i in range(0, length))

print(res)
mkyfhy

 

Using only ASCII lowercase characters isn't going to produce particularly strong passwords. Therefore you could use all printable characters:

 

import string
import random

length = 12
chars = string.printable

res = ''.join(random.choice(chars) for i in range(0, length))

print(res)
t4D(^qB 7}Dd

 

A more elaborate solution would be to selectively combine different character sets based on boolean conditions:

 

import string
import random

length = 12
upper = True
lower = True
digits = True
punct = True
white = False

chars = ''

if upper:
   chars = chars + string.ascii_uppercase
if lower:
   chars = chars + string.ascii_lowercase
if digits:
   chars = chars + string.digits
if punct:
   chars = chars + string.punctuation
if white:
   chars = chars + string.whitespace
   
res = ''.join(random.choice(chars) for i in range(0, length))

print(res)
cl{n'Q5pB9+N