Python Forum
Re.start() & Re.end()
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Re.start() & Re.end()
#1
Task
You are given a string S.
Your task is to find the indices of the start and end of string k in S.

solution that someone came to
S = input()
k = input()

import re
pattern = re.compile(k)
r = pattern.search(S)
if not r: 
    print(-1,-1)
while r:
    print('({0},{1})'.format(r.start(), r.end()-1)) 
    r = pattern.search(S, r.start()+1)
I could use some help in uderstanding it - how while loop works here is not clear to me. I understand that .start() and .end() give indices of k in S. Is this correct? Secondly, why decrease of r.end() by one? And what this line
r = pattern.search(S, r.start()+1)
means? Does it start search for k in S from second indice?
Reply
#2
As often in python, intervals a-b are semi-opened intervals [a, b). For example range(5,9) contains the number 5 but not the number 9. The same thing happens with r.start() and r.end(). The former is the index of the beginning of the occurrence of the pattern in the string, and the latter is the index immediately after the end of the occurrence of the pattern. For example re.compile('foo').search('foobar') has a start index of 0 and an end index of 3. But 3 is the index of the letter b in 'foobar'.

For the second question yes it starts search from the second indice.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020