0

As the title says, I have 2 strings, something like:

string = """
for i in x:
    for y in z[i]:
        print y
"""
s2 = "for"

What I want to get is:

[1, 17] # positions where "for" starts in string..

Is there any built-in function for this, or a better way than multiple finds??

pradyunsg
  • 18,287
  • 11
  • 43
  • 96

1 Answers1

1

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]
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343