Python如何检查输入是否只包含某些字符?

Python如何检查输入是否只包含某些字符?,python,Python,我试图让我的代码检查用户输入是否只包含以下字符:“!$%^&*()_-+=” 如果它包含任何其他字符,则应减去点数。我尝试过这个,但它不能正常工作: if "a-z" not in password and "A-Z" not in password and "0-9" not in password: points = points - 1 我怎样才能解决这个问题 谢谢您可以通过转义上面列出的字符来使用正则表达式: import re s = "_%&&^$" if

我试图让我的代码检查用户输入是否只包含以下字符:
“!$%^&*()_-+=”

如果它包含任何其他字符,则应减去点数。我尝试过这个,但它不能正常工作:

if "a-z" not in password and "A-Z" not in password and "0-9" not in password:
    points = points - 1
我怎样才能解决这个问题


谢谢

您可以通过转义上面列出的字符来使用正则表达式:

import re
s = "_%&&^$"
if not re.findall("^[\!\$\%\^\&\*\(\)\_\-\+\=]+$", s):
    points -= 1
我会用正则表达式

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

正如其他人所说,您可以使用正则表达式。类似这样的生成器表达式也适用:

points -= sum(1 for x in password if x not in '!$%^&*()_-+=')
您希望“密码”包含这些字符吗
“!$%^&*()_-+=”
或者您希望密码不包含它们吗?通过阅读你的问题,我会认为这是第一个问题,但通过你的“代码尝试”,我会认为你想做其他事情