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.py599 chars20 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