How to find all occurrences of a pattern and their indices in Python

python, regex, shortcut, string

Solution

python `re` module to the rescue.

>>> import re
>>> [x.start() for x in re.finditer('foo', 'foo foo foo foo')]
[0, 4, 8, 12]

`re.finditer` returns a generator, what this means is that instead of using list-comprehensions you could use in in a `for-loop` which would be more memory efficient.

You could extend this to get the span of your pattern in the given text. i.e. the start and end index.

>>> [x.span() for x in re.finditer('foo', 'foo foo foo foo')]
[(0, 3), (4, 7), (8, 11), (12, 15)]

Isn't Python Awesome :) couldn't stop myself from quoting XKCD, downvotes or no downvotes...

Problem

Is there a pythonian or shorthand way to get all pattern occurrences from a string and their indices? I can write a method that does it, I'm just wondering if there's a super short one-liner or something :)

Original source