How to Generate Random Password or String Securely in Python – Examples & Explanation

Random string or password generator
There are many ways to securely generate the random password or a string of specific length in Python Programming Language. Every Python random password or string generator method has its own merits and demerits. Fortunately, Python has some very easy ways to securely generate random passwords or strings of the specific length. You can use any combination of characters like alphabets of uppercase or lowercase, digits, and punctuation. Most common use of random string generators are passwords, API keys and software serial numbers, etc. There are various examples provided with the explanation in the example sections of this article to choose from according to your requirement.

Punctuation characters are used to generate more secure passwords in the example codes. If you don’t want to use punctuation characters such as [{:, you can easily remove punctuation characters by modifying the example code or remove string.punctuation variable found in the code snippets.

Following are some simple and useful random string or password generator code snippets examples. You are free to adopt it or modify it according to your requirements.


Example of Generating Random Password or String with Alphabets of Uppercase or Lowercase, Digits, and Punctuation of Specific Length

Following example generates a random password string of 10 characters with 3 uppercase, 3 lowercase alphabets, 2 digits and 2 special characters. This may not be the elegant way but meets most of the password requirement. The length and character representation can be adjusted according to your need by passing the parameters.

import random
import string

# uchars = Uppercase charaters
# lchars =  Lowercase charaters
# dchars = Digits
# schars = Punctuation or Special Charaters

def get_random_string(uchars = 3, lchars = 3, dchars = 2, schars = 2):
    # Generates a 10 characters long random string
    # with 3 upper case, 3 lowe case, 2 digits and 2 special characters

    str_uchars, str_lchars, str_dchars, str_schars = '', '', '', ''

    for i in range(uchars):
        str_uchars += random.SystemRandom().choice(string.ascii_uppercase)

    for i in range(lchars):
        str_uchars += random.SystemRandom().choice(string.ascii_lowercase)

    for i in range(dchars):
        str_uchars += random.SystemRandom().choice(string.digits)

    for i in range(schars):
        str_uchars += random.SystemRandom().choice(string.punctuation)

    random_str = str_uchars + str_lchars + str_dchars + str_schars
    random_str = ''.join(random.sample(random_str, len(random_str)))
    return random_str

print('Your Random String-1:', get_random_string())

# generates five uppercase, 5 lowercase, 3 digits and 2 punctuation
print('Your Random String-2:', get_random_string(5, 5, 3, 2))

# Your output will be different

Your Random String-1: -oUfH78eU(
Your Random String-2: LnuDsJ]61qHpD4~


Simple Example of Generating Random Password or String

This is a simple password or random string generator using Python built-in random and string library. It is a good startup for beginners and provides a decent control over the random string generation, in most cases, acceptable by the user. By default, it generates a variable length string of 10 to 15 characters long with letters, digits, and punctuation. The length of random string generation can easily be controlled by passing the desired length in arguments.

import os, random, string

def get_random_string(min_chars=10, max_chars=15):
    all_chars = string.ascii_letters + string.digits + string.punctuation
    random.seed = (os.urandom(1024))  # this line can be removed
    random_str = "".join(random.choice(all_chars)
                         for _ in range(random.randint(min_chars, max_chars)))
    return random_str

print('Your Random String-1:', get_random_string())
print('Your Random String-2:', get_random_string())

# Your output will be different

Your Random String-1: tW(It1BKW5q
Your Random String-2: 0*u'Um%}NHuiNg"


Simple Example of Generating Random Password or String without Duplicate Consecutive Characters

This is a simple password or random string generator with Python built-in random library dependency. It generates a random password or string with specified characters long as an argument. This function also removes duplicate consecutive characters and make random password or string strong.

import random

pass_chars = ['abcdefghijklmnopqrstuvwxyz',
              '^!\$%&/()=?{[]}+~#-_.:,;<>|\\', ]

def get_random_password(length=15):
    pwd = []
    chars = random.choice(pass_chars)
    while len(pwd) < length:
        chars = random.choice(list(set(pass_chars) - set([chars])))
    return "".join(pwd)

print('Your Random String-1:', get_random_string())
print('Your Random String-2:', get_random_string())

# Your output will be different

Your random password-1: 9O6O\s\h3f1x0[l
Your random password-2: $0SgBo2GmT=0Q!7


Example of Generating Random Password or String Using Lamda Expression

import random
import string

get_random_string = lambda length, \
                  all_chars = string.ascii_letters + string.digits + string.punctuation: \
                  "".join([list(set(all_chars))[random.randint(0, len(list(set(all_chars)))-1)] \
                  for _ in range(length)])

print("Random string-1:", get_random_string(10))
print("Random string-2:", get_random_string(15))
print("Random string-3:", get_random_string(20))

# Your output will be different

Random string-1: I8XCL^^;A+
Random string-2: gj`5hI#DLzaB~9&
Random string-3: sFeN9g~K*AK:eFsQ]NPm


Example of Generating Random Password or String Using with Graphical User Interface (Tkinter)

import os, random, string
from tkinter import *

def get_random_string(max_chars=10):
    chars = string.ascii_letters + string.digits + string.punctuation
    random.seed = (os.urandom(1024))
    random_str = ''.join(random.choice(chars) for _ in range(max_chars))
    return random_str

def update_random_string():
    # updates the user-interface textbox
        count_chars = int(pass_len.get())
    except ValueError:

    pass_box.delete(0, 'end')
    pass_box.insert(0, get_random_string(count_chars))

mainWindow = Tk()
mainWindow.title(' Simple Password Generator')

mainWindow.resizable(0, 0)

frame = Frame(mainWindow)

frame.pack(side=TOP, pady=10, padx=10, fill=X, expand=1)

Label(frame, text="Password Length: ", anchor=E).grid(row=0, column=0, sticky=E)

pass_len = Entry(frame)
pass_len.insert(0, '10')
pass_len.grid(row=0, column=1)

btn = Button(frame, text="Generate Password")
btn['command'] = lambda: update_random_string()
btn.grid(row=0, column=2, rowspan=1, padx=10, ipadx=10)

Label(frame, text="Generated password: ", anchor=E).grid(row=1, column=0, sticky=E)
pass_box = Entry(frame)
pass_box.grid(row=1, column=1)


# Open main window


Example of Generating Random Password or String Using uuid()

This is the simplest password or random string generator available in Python. It generates Universal Unique Identifier using the RFC 4122. It is a 36 characters long string with 4 dashes. It is good for beginners but doesn’t provide an elegant control over the random string generation. It always generates a fixed length 36 characters long string which are, in most cases, not desirable by the user.

import uuid

# Generates a UUID from a host ID, sequence number, and the current time
print('Random String-1: ', uuid.uuid1())

# Generates a random UUID.
print('Random String-4: ', uuid.uuid4())

# Your output will be different

Random String-1: dab7ca06-d4bb-11e6-81bd-b147b547af34
Random String-4: 7c0abf9f-e7a2-4a18-9c23-32248d2dc482

Final Words

All random string generation functions and techniques are provided as a startup. You can freely use it in your development or production environments. You should keep in mind that these algorithms are not 100% safe. There are chances that a hacker can decode or break your random passwords. Therefore, some special methods and cryptic techniques should be used to secure your such information from hackers or other similar threats.