使用.find搜索列表中的字符串

时间:2015-06-09 04:23:15

标签: python string list

我想遍历一个字符串列表......

例如:

list_of_strings = ['Hello!, my name is Carl', 'Hello!, my name is Steve', 'Hello!, my name is Betty']

我想遍历列表项并搜索“Hello!”的位置在每种情况下,在字符串内记录它的位置。

有什么想法吗?

5 个答案:

答案 0 :(得分:2)

使用string.find方法。

>>> phrase = 'Hello, my name is Syko'
>>> phrase.find('Hello')
0

答案 1 :(得分:2)

您可以尝试list comprehensions

[(s,s.lower()。index(' hello'))对于list_of_strings中的s,如果s.lower()==' hello']

答案 2 :(得分:2)

使用list comprehension收集所需字符串的索引:

>>> list_of_strings = ['Hello!, my name is Carl', 'Hello!, my name is Steve', 'Hello!, my name is Betty', 'My Name is Josh']
>>> [s.find('Hello!') for s in list_of_strings]
[0, 0, 0, -1]

请注意,否定1表示最终字符串不包含您要查找的值。

答案 3 :(得分:1)

>>> list_of_strings = ['Hello!, my name is Carl', 'Hello!, my name is Steve', 'Hello!, my name is Betty']

>>> indices = [position for position, phrase in enumerate(list_of_strings) if 'Hello!' in phrase]
>>> print indices
[0, 1, 2]

使用理解列表,遍历列表并检查字符串中是否包含Hello!字符串,如果是,则将position附加到匹配列表。

注意:enumerate内置版为您带来了列表中每个元素的索引。

答案 4 :(得分:1)

如果您要搜索列表中的多个项目,请说出Hello和name

find = lambda searchList, elem: [[i for i, x in enumerate(searchList) if x == e] for e in elem] find(list_of_strings,['Hello','name'])

输出是一个列表,其中包含您按列出的顺序搜索的元素的位置