小编典典

Python-如何找到所有出现的子串?

python

Python具有string.find()string.rfind()获取字符串中子字符串的索引。

我想知道是否有类似的东西string.find_all()可以返回所有找到的索引(不仅是开头的第一个,还是结尾的第一个)。

例如:

string = "test test test test"

print string.find('test') # 0
print string.rfind('test') # 15

#this is the goal
print string.find_all('test') # [0,5,10,15]

阅读 1009

收藏
2020-02-10

共1个答案

小编典典

没有简单的内置字符串函数可以满足你的需求,但是你可以使用功能更强大的正则表达式:

import re
[m.start() for m in re.finditer('test', 'test test test test')]
#[0, 5, 10, 15]

如果要查找重叠的匹配项,先行搜索将做到:

[m.start() for m in re.finditer('(?=tt)', 'ttt')]
#[0, 1]

如果你想要一个没有重叠的反向查找全部,则可以将正向和负向超前组合成这样的表达式:

search = 'tt'
[m.start() for m in re.finditer('(?=%s)(?!.{1,%d}%s)' % (search, len(search)-1, search), 'ttt')]
#[1]

re.finditer返回一个generator,因此你可以更改[]上面的()以获得一个Generator而不是一个列表,如果只迭代一次结果,则列表会更有效。

2020-02-10