You either use multiple finds, or use a regular expression and re.finditer()
:
[match.start() for match in re.finditer(re.escape(s2), string)]
re.finditer()
yields match objects, and we use the re.MatchObject.start()
method here to just pick out the start index of matches found.
I used re.escape()
to prevent regular expression meta characters in s2
to be interpreted to make sure the behaviour is the same as multiple str.find()
calls.
Demo:
>>> import re
>>> string = """
... for i in x:
... for y in z[i]:
... print y
... """
>>> s2 = "for"
>>> [match.start() for match in re.finditer(re.escape(s2), string)]
[1, 17]