Python:如果列表包含字符串打印列表中包含它的所有索引/元素

5 python string search loops list

我能够检测到匹配,但无法定位它们在哪里。

鉴于以下列表:

['A second goldfish is nice and all', 3456, 'test nice']
Run Code Online (Sandbox Code Playgroud)

我需要搜索匹配(即“不错”)并打印包含它的所有列表元素。理想情况下,如果要搜索的关键字“不错”,结果应该是:

'A second goldfish is nice and all'
'test nice'
Run Code Online (Sandbox Code Playgroud)

我有:

list = data_array
string = str(raw_input("Search keyword: "))
print string
if any(string in s for s in list):
    print "Yes"
Run Code Online (Sandbox Code Playgroud)

所以它找到匹配并打印关键字和“是”,但它没有告诉我它在哪里。

我应该遍历列表中的每个索引以及每次迭代搜索“s 中的字符串”还是有更简单的方法来做到这一点?

Bre*_*nks 3

尝试这个:

list = data_array
string = str(raw_input("Search keyword: "))
print string
for s in list:
    if string in str(s):
        print 'Yes'
        print list.index(s)
Run Code Online (Sandbox Code Playgroud)

编辑为工作示例。如果您只想要第一个匹配的索引,您也可以在 if 语句评估 true 后中断