create a password with at least two uppercase letters in python

Here's a simple code snippet that generates a random password that includes at least two uppercase letters using the string and random modules in Python:

main.py
import string
import random
import re

def generate_password():
    # Define character sets for each password component
    uppercase_letters = string.ascii_uppercase
    lowercase_letters = string.ascii_lowercase
    digits = string.digits
    symbols = string.punctuation.replace("_", "")
    
    # Generate a password with at least two uppercase letters
    password = ""
    while True:
        password = "".join(random.choice(uppercase_letters + lowercase_letters + digits + symbols) for i in range(8))
        if len(re.findall("[A-Z]", password)) >= 2:
            break
    
    return password
605 chars
20 lines

The generate_password() function uses the random.choice() method to randomly select characters from the character sets for uppercase and lowercase letters, digits, and symbols. It then checks if there are at least two uppercase letters in the generated password using a regular expression pattern ("[A-Z]") and the re.findall() method. If there are at least two uppercase letters, the function returns the password. Otherwise, it generates another password until there are at least two uppercase letters.

gistlibby LogSnag