I have a string '10101', need to find out the occurrence of '101' from the string. There are 2 occurrences of '101' first occurrence is from index 0 to 3 and the second occurrence is from index 3 to 5. How do I get this done using python?
Asked
Active
Viewed 39 times
0
-
I think your example indexes are off.0-2 and 2-4 ? – Ryan Haining Oct 16 '19 at 18:20
-
nobody said anything about this being about `regex`... I like the pure python version ;-) – FObersteiner Oct 16 '19 at 18:48
1 Answers
1
Adapted from this answer:
import re
s = "10101"
matches = re.finditer(r'(?=(101))', s)
results = [m[1] for m in matches]
print(results) # -> ['101', '101']
See the linked answer for details about how this works.
If you're using Python 3.5 or earlier, replace m[1]
with m.group(1)
.

wjandrea
- 28,235
- 9
- 60
- 81