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

12th Jun 2020, 4:10 PM
roja ch
roja ch - avatar
7 Respostas
+ 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=' ')
12th Jun 2020, 7:55 PM
Lothar
Lothar - avatar
+ 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())
12th Jun 2020, 5:22 PM
Russ
Russ - avatar
+ 1
Can you show us what you've got so far?
12th Jun 2020, 4:15 PM
HonFu
HonFu - avatar
+ 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
12th Jun 2020, 4:48 PM
Bilbo Baggins
Bilbo Baggins - avatar
+ 1
Thanks all.. Got it now🙂
14th Jun 2020, 11:53 AM
roja ch
roja ch - avatar
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
12th Jun 2020, 4:24 PM
roja ch
roja ch - avatar
12th Jun 2020, 4:25 PM
Bilbo Baggins
Bilbo Baggins - avatar