Search code examples
pythonwhile-loopspecial-characters

Check for special characters in Python while loop


Below is code for a password generator which I've written using Python3 and tkinter. I'm having difficulty with the last line of code and any(c in spec for c in password). The while loop does not terminate when I add this last line to the if statement in the while loop. I've looked at all the other answers online for "check string for special characters" and can't find a solution to make my while loop work. The last line of my code should check if there is any special characters in the password, if not, then generate password again.

import string
import secrets

alphabet = string.ascii_letters + string.digits + string.punctuation
spec = string.punctuation
while True:
    password = ''.join(secrets.choice(alphabet) for i in range(12))
    if (any(c.islower() for c in password)
        and any(c.isupper() for c in password)
        and any(c.isdigit() for c in password)
        and any(c in spec for c in password)):
        break

Solution

  • The code and any(c in spec for c in password) does in fact work. After PyxlDavon pointed out that my code does work, I closed and restarted my python interpreter and the code did work. So my only conclusion is that my python interpreter became unstable for some unkown reason. I haven't seen this code style in any other related questions. I apologize for answering my own question. I got the idea for this code from this link: https://www.codespeedy.com/detect-if-a-string-contains-special-characters-or-not-in-python/#:~:text=To%20check%20if%20a%20string,special%20characters%20from%20the%20string.