Re.start() & Re.end()

You can find this problem on hakerrank

Problem Statement:

start() & end() These expressions return the indices of the start and end of the substring matched by the group.


>>> import re 
>>> m ='\d+','1234')
>>> m.end() 
>>> m.start() 

Task You are given a string S. Your task is to find the indices of the start and end of string K in S.

Input Format The first line contains the string S. The second line contains the string K.

Constraints 0 < len(S) < 100

0 < len(K) < len(S)

Output Format Print the tuple in this format: (start _index, end _index). If no match is found, print (-1, -1).

Sample Input


Sample Output

(0, 1) 
(1, 2) 
(4, 5)

Solution 1

Using re:

import re
s = input()
k = input()

substring = re.compile(k)
r =

if not r: 
    print("(-1, -1)")
    while r:
        print("({}, {})".format(r.start(), r.end() - 1))
        r =,r.start() + 1)

Solution 2

Without using any library:

S = input()
k = input()
check = False
for i in range(len(S)-len(k)+1):
    if S[i:i+len(k)]==k:
        check = True
        print("({}, {})".format(i,i+len(k)-1))
if check==False:
    print("(-1, -1)")

Happy Coding!

Follow us on Instagram @programmersdoor

Join us on Telegram @programmersdoor

Please write comments if you find any bug in above code/algorithm, or find other ways to solve the same problem.

Follow Programmers Door for more.

#blog #interview #placement #learn #ComputerScience #Engineering

160 views0 comments

Recent Posts

See All