Navbar menu

HackerRank Python Solution - Regex and Parsing - Re.start() & Re.end()

start() & end():
  • These expressions return the indices of the start and end of the substring matched by the group.
>>> import re
>>> m = re.search(r'\d+','1234')
>>> m.end()
4
>>> m.start()
0
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:

aaadaa
aa
Sample Output:

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

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

pattern = re.compile(k)
match = pattern.search(s)

if not match:
    print('(-1, -1)')

while match:
    print('({0}, {1})'.format(match.start(), match.end() - 1))
    match = pattern.search(s, match.start() + 1)
Note: The problem statement is given by hackerrank.com but the solution is generated by the Geek4Tutorial admin. We highly recommend you solve this on your own, however, you can refer to this in case of help. If there is any concern regarding this post or website, please contact us using the contact form. Thank you!

No comments:

Post a Comment