简体   繁体   English

如何解决/检查字符串中的字符是否不是不允许的字符?

[英]How to address/check whether a character in a string isn't a disallowed character?

To be more specific, if I have a string as such: 更具体地说,如果我有这样的字符串:

string = "app-_l#e"

Now, all letter, numerical, hyphens, and underscores are allowed; 现在,允许使用所有字母,数字,连字符和下划线; though any other character is not. 尽管没有其他字符。

Is there a function that would filter out designated types and/or single characters? 有没有可以过滤指定类型和/或单个字符的功能?

You can use str.translate to remove the allowed chars from the string leaving you with an empty string if only allowed chars are in the string or else a string of forbidden chars: 您可以使用str.translate从字符串中删除允许的字符,如果字符串中仅包含允许的字符,或者是一串禁止的字符,则留下一个空字符串:

from string import ascii_letters, digits

s = "app-_l#e"
# if the string is empty
if not s.translate(None, "-_" + ascii_letters + digits):
    # string only contains allowed characters

After translating your input string would look like: 翻译后,您的输入字符串如下所示:

In [7]: from string import ascii_letters, digits

In [8]: s = "app-_l#e"

In [9]: s.translate(None, "-_" + ascii_letters + digits)
Out[9]: '#'

Or keep a set of allowed chars: 或保留一允许的字符:

from string import ascii_letters, digits
allowed = set("-_" + ascii_letters + digits)
s = "app-_l#e"
if all(ch in allowed for ch in s):
     # string only contains allowed characters

Of you want to find out what forbidden characters are in the string either print s.translate(None, "-_" + ascii_letters + digits) which will only have any chars not allowed or iterate in a for loop: 您想找出字符串中哪些禁忌字符,或者print s.translate(None, "-_" + ascii_letters + digits) ,该字符将不允许任何字符或在for循环中进行迭代:

from string import ascii_letters, digits
allowed = set("-_" + ascii_letters + digits)
s = "app-_l#e"
disallowed = [ch for ch in s if ch not in allowed] 

You can use re , However note that it will be slower. 您可以使用re ,但是请注意,它将变慢。

>>> import re
>>> pat = re.compile(r'[\d|\w|\-|_]+$')
>>> if pat.match("app-_l#e"):
...     print True
... else:
...     print False
... 
False

And a matching example 和一个匹配的例子

>>> if pat.match("apple123_-"):
...     print True
... else:
...     print False
... 
True

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

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