Skip to main content
 首页 » 编程设计

python之使用 .find 在列表中搜索字符串

2025年05月04日21Renyi-Fan

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

例如:

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

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

有什么想法吗?

请您参考如下方法:

使用 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 如何表明最终字符串不包含您要查找的值。