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
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...
>>> txt = '''first line
... second line
... third line'''
>>> txt.rfind('\n')
22
>>> txt.rindex('\n')
22