Well, is regexp is out of the question, consider this generator code:
def find_all(target, substring):
current_pos = target.find(substring)
while current_pos != -1:
yield current_pos
current_pos += len(substring)
current_pos = target.find(substring, current_pos)
We use 'find' optional argument of setting the start index of the search, and every time use the last one found, plus the length of the sub-string (so we do't get the same result every time).
If you want to get overlapping matches, use + 1
and not len(substring)
.
You can 'list(find_all('abbccbb', 'bb'))'
to get an actual list of indexs.
Just a side note: generators (aka, the yield
keyword) are more memory efficient than plain lists, and while loops have far less overhead than recursion (and are also much easier to read if you are a human being).