user8901745
user8901745

Reputation:

Python how to check if an input only contains certain characters?

I am trying to get my code to check if a user input only contains the following characters: "!$%^&*()_-+="

If it contains any other characters then points should be subtracted. I tried this but it doesn't work properly:

if "a-z" not in password and "A-Z" not in password and "0-9" not in password:
    points = points - 1

How can I fix this?

Thank you

Upvotes: 1

Views: 164

Answers (3)

jboyce
jboyce

Reputation: 31

As others have said you can use regex. A generator expression like this works too:

points -= sum(1 for x in password if x not in '!$%^&*()_-+=')

Upvotes: 0

Trenton Telge
Trenton Telge

Reputation: 488

I would use regex.

import re
if not (re.compile("[\"\!\$\%\^\&\*\(\)_\-\+=\"]+").match(s)): #Subtract points

Upvotes: 0

Ajax1234
Ajax1234

Reputation: 71451

You can use use a regular expression by escaping the characters you listed above:

import re
s = "_%&&^$"
if not re.findall("^[\!\$\%\^\&\*\(\)\_\-\+\=]+$", s):
    points -= 1

Upvotes: 2

Related Questions