Python 如何检查字符串中的特殊字符?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19970532/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to check a string for a special character?
提问by Chuvi
I can only use a string in my program if it contains no special characters except underscore _
. How can I check this?
我只能在我的程序中使用一个字符串,如果它不包含除下划线之外的特殊字符_
。我该如何检查?
I tried using unicodedata library. But the special characters just got replaced by standard characters.
我尝试使用 unicodedata 库。但是特殊字符刚刚被标准字符取代。
采纳答案by thefourtheye
You can use string.punctuation
and any
function like this
您可以像这样使用string.punctuation
和any
运行
import string
invalidChars = set(string.punctuation.replace("_", ""))
if any(char in invalidChars for char in word):
print "Invalid"
else:
print "Valid"
With this line
有了这条线
invalidChars = set(string.punctuation.replace("_", ""))
we are preparing a list of punctuation characters which are not allowed. As you want _
to be allowed, we are removing _
from the list and preparing new set as invalidChars
. Because lookups are faster in sets.
我们正在准备一个不允许使用的标点符号列表。由于您希望_
被允许,我们正在_
从列表中删除并准备新的集合为invalidChars
。因为在集合中查找速度更快。
any
function will return True
if atleast one of the characters is in invalidChars
.
any
True
如果至少有一个字符在中,则函数将返回invalidChars
。
Edit:As asked in the comments, this is the regular expression solution. Regular expression taken from https://stackoverflow.com/a/336220/1903116
编辑:正如评论中所问,这是正则表达式解决方案。取自https://stackoverflow.com/a/336220/1903116 的正则表达式
word = "Welcome"
import re
print "Valid" if re.match("^[a-zA-Z0-9_]*$", word) else "Invalid"
回答by U2EF1
You will need to define "special characters", but it's likely that for some string s
you mean:
您将需要定义“特殊字符”,但对于某些字符串,s
您的意思很可能是:
import re
if re.match(r'^\w+$', s):
# s is good-to-go