the*_*eye 45
你可以像这样使用string.punctuation和any运作
import string
invalidChars = set(string.punctuation.replace("_", ""))
if any(char in invalidChars for char in word):
print "Invalid"
else:
print "Valid"
Run Code Online (Sandbox Code Playgroud)
有了这条线
invalidChars = set(string.punctuation.replace("_", ""))
Run Code Online (Sandbox Code Playgroud)
我们正在准备一个不允许的标点字符列表.正如您所希望的那样_,我们_将从列表中删除并准备新的集合invalidChars.因为查找在集合中更快.
anyTrue如果至少有一个字符在,则函数将返回invalidChars.
编辑:如评论中所述,这是正则表达式解决方案.正则表达式取自/sf/answers/23535431/
word = "Welcome"
import re
print "Valid" if re.match("^[a-zA-Z0-9_]*$", word) else "Invalid"
Run Code Online (Sandbox Code Playgroud)
您将需要定义“特殊字符”,但对于某些字符串,s您的意思很可能是:
import re
if re.match(r'^\w+$', s):
# s is good-to-go
Run Code Online (Sandbox Code Playgroud)