Reputation: 4301
I have a string called s:
s = "Temperature is 15 degree Celsius. It is expected to be hotter tomorrow, say, 20 degree Celsius."
I want to find the word "degree"
which is nearest to "tomorrow"
in backward direction.
First, I find the position of 'tomorrow'
, then I search backward from the previously found position to find the word "degree"
.
The first step is:
index = s.index('tomorrow')
How to do the second step?
Upvotes: 0
Views: 395
Reputation: 73498
This recursive generator function produces all the index pairs of two substrings within another string. Then you can use min
with an appropriate key function to find the one where the indexes are closest:
def pairs(s, s1, s2, i=0):
i1 = s.find(s1, i) # start looking at index i
i2 = s.find(s2, i1) # start looking at index i1
if i2 < 0 or i1 < 0: # one wasn't found
return
yield i1, i2
yield from pairs(s, s1, s2, i2)
s = 'xx ab cd xxx ab xx cd'
s1, s2 = 'ab', 'cd'
l = list(pairs(s, s1, s2))
# [(3, 6), (13, 19)]
min(l, key=lambda x: x[1]-x[0]) # indexes of s1, s2 in s where they are closest
# (3, 6)
Upvotes: 0
Reputation: 1112
Find the position of "tomorrow" as you said, next, you use rfind (right find) and you will find the nearest position to "tomorrow".
s = "Temperature is 15 degree Celsius. It is expected to be hotter tomorrow, say, 20 degree Celsius."
index = s[0:s.index("tomorrow")].rfind("degree")
Upvotes: 0
Reputation: 804
Is this what you want?
index = s.index('tomorrow')
index2 = s.rfind('degree', 0, index)
Upvotes: 3