+ 2
In Python, How to find the start and end indices of the matching string K in the original string S?
Ex: S=aaadaa and K=aa Here we can find string "aa" at 3 positions So need to print those 3 positions start and end positions as output 0/p :(0, 1), (1, 2), (4, 5)
7 Respuestas
+ 4
Here a version with a for loop, but regex would be the preferred solution.
# using for loop:
txt = 'aaadaaxxaaaaax._::axaaaa'
s = 'aaaa'
for pos, i in enumerate(range(len(txt)-len(s)+1)):
if txt[i:i+len(s)] == s:
print((pos, pos+len(s)-1),end=' ')
+ 2
As Bilbo Baggins suggested, a cheeky lookahead will help with the overlapping matches!
import re
s=list(re.finditer(r'a(?=a)', 'aaadaa'))
for e in s:
print(e.start(), e.end())
+ 1
Can you show us what you've got so far?
+ 1
e.end() must be replaced with e.end()-1
and in the link I suggested you is written that, for overlapping substrings, lookahead is required
+ 1
Thanks all.. Got it now🙂
0
I just tried with below logic :
S=list(re.finditer(r'aa', aaadaa))
for e in s:
print(e.start(), e.end())
Got O/p as :
0 2
4 6
But expected output as
0 1
1 2
4 5
0
and do not forget google 😉
https://stackoverflow.com/questions/4664850/how-to-find-all-occurrences-of-a-substring