Skip to main content
 首页 » 编程设计

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

2025年05月04日24kenshinobiy

更具体地说,如果我有这样一个字符串:

string = "app-_l#e" 

现在,允许使用所有字母、数字、连字符和下划线;尽管任何其他字符都不是。

是否有过滤指定类型和/或单个字符的功能?

请您参考如下方法:

您可以使用 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 

翻译后您的输入字符串将如下所示:

In [7]: from string import ascii_letters, digits 
 
In [8]: s = "app-_l#e" 
 
In [9]: s.translate(None, "-_" + ascii_letters + digits) 
Out[9]: '#' 

或者保留一个set允许的字符数:

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 

如果你想找出字符串中有哪些禁止字符 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]