如果字符串中包含除了下划线符号_
之外的特殊字符,我在程序中只能使用它。如何检查?
我试过使用unicodedata库, 但特殊字符只是被替换为标准字符。
您可以像这样使用string.punctuation
和any
函数。
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
的新集合。因为在集合中进行查找更快。
any
函数将在至少有一个字符在invalidChars
中时返回True
。
编辑: 根据评论要求,这是正则表达式解决方案。正则表达式取自https://dev59.com/9HRC5IYBdhLWcg3wUvQS#336220
word = "Welcome"
import re
print "Valid" if re.match("^[a-zA-Z0-9_]*$", word) else "Invalid"
你需要定义“特殊字符”,但对于某些字符串s
,你可能是指:
import re
if re.match(r'^\w+$', s):
# s is good-to-go
for character in my_string
if not (character.isnumeric() and character.isspace() and character.isalpha() and character != "_")
print(" \(character)is special"
像Cybernetic中的方法一样,为了获取那些额外的字符,需要修改函数的第二行:
regex= re.compile('[@_!#$%^&*()<>?/\|}{~:]')
改为
regex= re.compile('[@_!#$%^&*()<>?/\\|}{~:\[\]]')
其中\
和]
字符需要用\
进行转义。
因此完整代码如下:
import re
def detect_special_characer(pass_string):
regex= re.compile('[@_!#$%^&*()<>?/\\\|}{~:[\]]')
if(regex.search(pass_string) == None):
res = False
else:
res = True
return(res)
其他人的方法没有考虑空格。显然,没有人真正认为空格是特殊字符。
使用此方法检测特殊字符不包括空格:
import re
def detect_special_characer(pass_string):
regex= re.compile('[@_!#$%^&*()<>?/\|}{~:]')
if(regex.search(pass_string) == None):
res = False
else:
res = True
return(res)
"^[a-zA-Z0-9 _]*$"
。 - thefourtheye[^a-zA-Z0-9_]*$
不是应该把^
放在括号里面吗?这样对我来说是有效的。 - clabe45