如何检查字符串中的特殊字符? [英] How to check a string for a special character?
问题描述
我只能在我的程序中使用一个字符串,如果它不包含除下划线 _
之外的特殊字符.我该如何检查?
I can only use a string in my program if it contains no special characters except underscore _
. How can I check this?
我尝试使用 unicodedata 库.但是特殊字符只是被标准字符替换了.
I tried using unicodedata library. But the special characters just got replaced by standard characters.
推荐答案
你可以像这样使用 string.punctuation
和 any
函数
You can use string.punctuation
and any
function like this
import string
invalidChars = set(string.punctuation.replace("_", ""))
if any(char in invalidChars for char in word):
print "Invalid"
else:
print "Valid"
有了这条线
invalidChars = set(string.punctuation.replace("_", ""))
我们正在准备一个不允许使用的标点符号列表.由于您希望允许 _
,我们正在从列表中删除 _
并准备新的集合为 invalidChars
.因为在集合中查找速度更快.
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.
any
函数将返回True
.
正如评论中所问,这是正则表达式解决方案.取自 https://stackoverflow.com/a/336220/1903116
As asked in the comments, this is the regular expression solution. Regular expression taken from https://stackoverflow.com/a/336220/1903116
word = "Welcome"
import re
print "Valid" if re.match("^[a-zA-Z0-9_]*$", word) else "Invalid"
这篇关于如何检查字符串中的特殊字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!