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

Is there a python or abbreviated way to get all sample patterns from a string and their indices? I can write a method that does this, I'm just wondering if there is a super short single line or something else :)

+4
source share
1 answer

python re module for salvation.

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

re.finditer returns a generator , which means that instead of using list-comprehensions, you can use in in a for-loop , which will be more memory efficient.

You can expand this to get the range of your template in a given text. that is, the index of the beginning and end.

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

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

enter image description here

+14
source

All Articles