Find index of last occurrence of a substring in a string

前端 未结 9 1575
挽巷
挽巷 2020-11-27 10:36

I want to find the position (or index) of the last occurrence of a certain substring in given input string str.

For example, suppose the input string is

9条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-27 10:38

    Not trying to resurrect an inactive post, but since this hasn't been posted yet...

    (This is how I did it before finding this question)

    s = "hello"
    target = "l"
    last_pos = len(s) - 1 - s[::-1].index(target)
    

    Explanation: When you're searching for the last occurrence, really you're searching for the first occurrence in the reversed string. Knowing this, I did s[::-1] (which returns a reversed string), and then indexed the target from there. Then I did len(s) - 1 - the index found because we want the index in the unreversed (i.e. original) string.

    Watch out, though! If target is more than one character, you probably won't find it in the reversed string. To fix this, use last_pos = len(s) - 1 - s[::-1].index(target[::-1]), which searches for a reversed version of target.

提交回复
热议问题