【发布时间】:2013-11-27 01:02:01
【问题描述】:
如果字符串不包含除下划线_ 之外的特殊字符,我只能在我的程序中使用它。我怎样才能检查这个?
我尝试使用 unicodedata 库。但是特殊字符只是被标准字符替换了。
【问题讨论】:
如果字符串不包含除下划线_ 之外的特殊字符,我只能在我的程序中使用它。我怎样才能检查这个?
我尝试使用 unicodedata 库。但是特殊字符只是被标准字符替换了。
【问题讨论】:
如果一个字符不是数字、空格或 A-Z,那么它是特殊的
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)
【讨论】:
你可以像这样使用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。因为在集合中查找速度更快。
如果invalidChars中至少有一个字符,any函数将返回True。
编辑: 正如 cmets 中所要求的,这是正则表达式解决方案。取自https://stackoverflow.com/a/336220/1903116的正则表达式
word = "Welcome"
import re
print "Valid" if re.match("^[a-zA-Z0-9_]*$", word) else "Invalid"
【讨论】:
"^[a-zA-Z0-9 _]*$"
[^a-zA-Z0-9_]*$ 和括号内的^ 吗?这对我有用
您需要定义“特殊字符”,但对于某些字符串 s,您的意思可能是:
import re
if re.match(r'^\w+$', s):
# s is good-to-go
【讨论】: