[英]In Python, how to check if a string only contains certain characters?
[英]Python how to check if an input only contains certain characters?
我正在尝试获取代码以检查用户输入是否仅包含以下字符: "!$%^&*()_-+="
如果它包含任何其他字符,则应减去点。 我试过了,但是不能正常工作:
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 '!$%^&*()_-+=')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.