简体   繁体   中英

How to find the position of a substring before an position index?

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?

Is this what you want?

index = s.index('tomorrow')
index2 = s.rfind('degree', 0, index)

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM