如何找到具有特定条件的角色?

时间:2018-11-03 19:22:45

标签: python python-3.x

我想遍历一个字符串并找到一个不是字母,数字或_的字符。 @。这是我的代码:

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)

不幸的是,它在返回空间索引时没有检测到任何东西。

3 个答案:

答案 0 :(得分:3)

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,这就是为什么您的代码不打印任何内容的原因

答案 1 :(得分:3)

使用enumerate()至极返回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 

答案 2 :(得分:1)

Using a regex:

import re

pattern = re.compile('[^\d\w\.@]')
s = "saddas das"

for match in pattern.finditer(s):
    print(match.start())

Output

6

The pattern '[^\d\w\.@]' matches everything that is not a digit, not a letter, nor _, . or @.