Python has string.find()
and string.rfind()
to get the index of a substring in string.
I wonder, maybe there is something like string.find_all()
which can return all founded indexes (not only first from beginning or first from end)?
For example:
string = "test test test test"
print string.find('test') # 0
print string.rfind('test') # 15
#that's the goal
print string.find_all('test') # [0,5,10,15]
This does the trick for me using re.finditer
This thread is a little old but this worked for me:
Thus, we can build it ourselves:
No temporary strings or regexes required.
There is no simple built-in string function that does what you're looking for, but you could use the more powerful regular expressions:
If you want to find overlapping matches, lookahead will do that:
If you want a reverse find-all without overlaps, you can combine positive and negative lookahead into an expression like this:
re.finditer
returns a generator, so you could change the[]
in the above to()
to get a generator instead of a list which will be more efficient if you're only iterating through the results once.