Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 :)

like image 699
Aleksandar Savkov Avatar asked Dec 04 '22 11:12

Aleksandar Savkov


1 Answers

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...

enter image description here

like image 108
Srikar Appalaraju Avatar answered Feb 18 '23 06:02

Srikar Appalaraju