Find index of last occurrence of a substring in a string

前端 未结 9 1525
挽巷
挽巷 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:39

    The more_itertools library offers tools for finding indices of all characters or all substrings.

    Given

    import more_itertools as mit
    
    
    s = "hello"
    pred = lambda x: x == "l"
    

    Code

    Characters

    Now there is the rlocate tool available:

    next(mit.rlocate(s, pred))
    # 3
    

    A complementary tool is locate:

    list(mit.locate(s, pred))[-1]
    # 3
    
    mit.last(mit.locate(s, pred))
    # 3
    

    Substrings

    There is also a window_size parameter available for locating the leading item of several items:

    s = "How much wood would a woodchuck chuck if a woodchuck could chuck wood?"
    substring = "chuck"
    pred = lambda *args: args == tuple(substring)
    
    next(mit.rlocate(s, pred=pred, window_size=len(substring)))
    # 59
    

提交回复
热议问题