简体   繁体   English

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

[英]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 谢谢

You can use use a regular expression by escaping the characters you listed above: 您可以通过转义上面列出的字符来使用正则表达式:

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

I would use regex. 我会使用正则表达式。

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

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 '!$%^&*()_-+=')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM