Find index of last occurrence of a substring in a string

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

    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 "", line 1, in 
    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
    

提交回复
热议问题