我想循环一个字符串,并找到一个不是字母、数字或_的字符。@。这是我的代码:
mystr = "saddas das"
for x in range(0, len(mystr)):
if not(mystr[x].isdigit() or mystr[x].isalpha or mystr[x]=="@" or mystr[x]=="_" or mystr[x]=="."):
print (x)
不幸的是,当它返回空间的索引时,它没有检测到任何东西。
发布于 2018-11-03 11:25:22
for x in range(0, len(mystr)):
if not(mystr[x].isdigit() or mystr[x].isalpha() or mystr[x]=="@" or mystr[x]=="_" or mystr[x]=="."):
print (x)
您忘记添加()
:mystr[x].isalpha
。要调用函数,您应该执行mystr[x].isalpha()
。mystr[x].isalpha
总是被计算为True
,这就是为什么您的代码不打印任何东西的原因
发布于 2018-11-03 11:25:34
使用枚举()将返回pos和您迭代的字符:
mystr = "saddas das"
for pos,c in enumerate(mystr):
# change your conditions to make it easier to understand, isalpha() helps
if c.isdigit() or c.isalpha() or c in "@_.":
continue # do nothing
else:
print (pos)
输出:
6
发布于 2018-11-03 11:26:12
使用正则表达式:
import re
pattern = re.compile('[^\d\w\.@]')
s = "saddas das"
for match in pattern.finditer(s):
print(match.start())
输出
6
模式'[^\d\w\.@]'
匹配所有不是数字、字母、_
、.
或@
的东西。
https://stackoverflow.com/questions/53134736
复制