Python 在字符串中查找索引

Python find index in a string

我正在尝试打印下面这个字符串中单词的索引。现在的问题是它正在检查列表中的每个元素并且 returning false。如果单词不在列表中并且不检查每个元素,我如何才能使它成为 return "False"?

target = "dont"
string = "we dont need no education we dont need to thought control no we dont"
liste = string.split() 
for index, item in enumerate(liste):
        if target in item:
                print index, item
        else:
                print 'False'

输出:

False
1 dont
False
False
False
False
6 dont
False
False
False
False
False
False
13 dont

首先检查单词是否在列表中:

 if word not in liste:

因此,如果您想 return 将其放入函数中:

def f(t, s):
    liste = s.split()
    if t not in liste:
        return False
    for index, item in enumerate(liste):
        if t == item:
            print index, item
    return True

除非你想匹配子字符串它也应该是if t == item:,如果你想return所有的索引你可以return一个列表comp:

def f(t, s):
    liste = s.split()
    if t not in liste:
        return False
    return [index for index, item in enumerate(liste) if t == item]

我想这就是你想要的:

target = "dont"
string = "we dont need no education we dont need to thought control no we dont"
liste = string.split()
if target in liste:
    for index, item in enumerate(liste):
        if target == item:
            print index, item
else:
    print 'False'