Find index of last occurrence of a substring in a string

前端 未结 9 1447
挽巷
挽巷 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.

    0 讨论(0)
  • 2020-11-27 10:39

    You can use rfind() or rindex()
    Python2 links: rfind() rindex()

    >>> s = 'Hello StackOverflow Hi everybody'
    
    >>> print( s.rfind('H') )
    20
    
    >>> print( s.rindex('H') )
    20
    
    >>> print( s.rfind('other') )
    -1
    
    >>> print( s.rindex('other') )
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    ValueError: substring not found
    

    The difference is when the substring is not found, rfind() returns -1 while rindex() raises an exception ValueError (Python2 link: ValueError).

    If you do not want to check the rfind() return code -1, you may prefer rindex() that will provide an understandable error message. Else you may search for minutes where the unexpected value -1 is coming from within your code...


    Example: Search of last newline character

    >>> txt = '''first line
    ... second line
    ... third line'''
    
    >>> txt.rfind('\n')
    22
    
    >>> txt.rindex('\n')
    22
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2020-11-27 10:40

    Use the str.rindex method.

    >>> 'hello'.rindex('l')
    3
    >>> 'hello'.index('l')
    2
    
    0 讨论(0)
  • 2020-11-27 10:42

    Use .rfind():

    >>> s = 'hello'
    >>> s.rfind('l')
    3
    

    Also don't use str as variable name or you'll shadow the built-in str().

    0 讨论(0)
  • 2020-11-27 10:45

    If you don't wanna use rfind then this will do the trick/

    def find_last(s, t):
        last_pos = -1
        while True:
            pos = s.find(t, last_pos + 1)
            if pos == -1:
                return last_pos
            else:
                last_pos = pos
    
    0 讨论(0)
提交回复
热议问题