+1 vote
in Programming Languages by (66.8k points)
I want to find the index of all occurrences of a substring in a string using Python. What is the best Pythnoic way for it?

1 Answer

+1 vote
by (281k points)
Best answer

There could be several ways to find the indexes of a substring in a string. One of the Pythonic ways is to use the "re" library. The finditer() function returns an iterator yielding match objects over all non-overlapping matches for the RE pattern in the string. You can apply the start() function to the iterator returned by the finditer() function to find the indices.

Here is an example:

>>> import re

>>> aa="Hello, I am here. Hello, where are you?. Hello, find me"

>>> [m.start() for m in re.finditer("Hello",aa)]

[0, 18, 41]