Random Password Generator with Complexity Ensured

  • Share this:

Code introduction


This function generates a random password that ensures the password contains lowercase letters, uppercase letters, numbers, and special characters.


Technology Stack : random, string, re

Code Type : Generate random password

Code Difficulty : Intermediate


                
                    
import random
import string
import re
import math
import os
import sys
import datetime

def generate_random_password(length=12):
    if length < 4:
        raise ValueError("Password length must be at least 4 characters")
    characters = string.ascii_letters + string.digits + string.punctuation
    while True:
        password = ''.join(random.choice(characters) for i in range(length))
        if re.search(r"[a-z]", password) and re.search(r"[A-Z]", password) and re.search(r"\d", password) and re.search(r"[!@#$%^&*(),.?\":{}|<>]", password):
            break
    return password                
              
Tags: