Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python在字符串中查找索引_Python_List_Enumerate - Fatal编程技术网

Python在字符串中查找索引

Python在字符串中查找索引,python,list,enumerate,Python,List,Enumerate,我正在尝试打印下面这个字符串中单词的索引。现在的问题是,它正在检查列表中的每个元素,并返回false。如果单词不在列表中,并且没有检查每个元素,我如何使它返回“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):

我正在尝试打印下面这个字符串中单词的索引。现在的问题是,它正在检查列表中的每个元素,并返回false。如果单词不在列表中,并且没有检查每个元素,我如何使它返回“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:
因此,如果要返回,请将其放入函数中:

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
除非要匹配子字符串,否则如果t==item:,它也应该是
,如果要返回所有索引,可以返回列表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'

@我知道python,我以为你想
返回“False”
?您意识到打印不会返回,并且在python中,
False
是一个布尔值?
如果项中的目标将匹配子字符串,如果您认为子字符串匹配,则在使用in进行检查之前将不会进行点拆分。如何使输出为:not[1,6,13]in alist@Iknowpython,第二个代码返回
[1,6,13]
,如果你想让这个词也和列表一起返回,
返回t,[index for index,item in enumerate(liste)if t==item]->('dont',[1,6,13])
或者使用一个dictI only get:[1,6,13]前面没有“dont”。那么您没有添加上面的代码,因为发布时它会生成
('dont',[1,6,13])
,这是一个包含目标字符串和索引列表的元组