create a password with at least one symbol in python

You can create a random password with at least one symbol in Python by generating a string containing uppercase and lowercase letters, digits, and symbols using the string module, and then picking a random symbol from the string to insert into the password. Here's an example:

main.py
import string
import random

symbols = string.punctuation
letters_and_digits = string.ascii_letters + string.digits

def generate_password(length):
    password = ''
    while len(password) < length:
        # Add a random letter or digit
        password += random.choice(letters_and_digits)
        # If we haven't added a symbol yet, add one
        if len(password) < length and len(set(password) & set(symbols)) == 0:
            password += random.choice(symbols)
    return password

# Generate a password with at least one symbol and length 8
password = generate_password(8)
print(password)
599 chars
20 lines

This code defines a function generate_password that takes a length parameter and returns a random password of that length with at least one symbol. The function uses a while loop to construct the password character by character. For each character, it randomly chooses a letter or digit from letters_and_digits and appends it to the password. Then, if the password is still shorter than the desired length and no symbol has been added yet (checked with set(password) & set(symbols)), it randomly chooses a symbol from symbols and appends it to the password. The function returns the completed password.

To use the function, simply call it with the desired password length as the argument. The example code generates a password of length 8 and prints it to the console.

gistlibby LogSnag