Finding multiple occurrences of a string within a string in Python [duplicate]

Using regular expressions, you can use re.finditer to find all (non-overlapping) occurences:

>>> import re
>>> text="Allowed Hello Hollow"
>>> for m in re.finditer('ll', text):
         print('ll found', m.start(), m.end())

ll found 1 3
ll found 10 12
ll found 16 18

Alternatively, if you don’t want the overhead of regular expressions, you can also repeatedly use str.find to get the next index:

>>> text="Allowed Hello Hollow"
>>> index = 0
>>> while index < len(text):
        index = text.find('ll', index)
        if index == -1:
            break
        print('ll found at', index)
        index += 2 # +2 because len('ll') == 2

ll found at  1
ll found at  10
ll found at  16

This also works for lists and other sequences.

Leave a Comment