Find index of last occurrence of a substring in a string Find index of last occurrence of a substring in a string python python

Find index of last occurrence of a substring in a string


Use .rfind():

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

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


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


Use the str.rindex method.

>>> 'hello'.rindex('l')3>>> 'hello'.index('l')2