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 str = 'hello'
and the substring is target = 'l'
, then it should output 3.
How can I do this?
The rfind() method finds the last occurrence of the specified value. The rfind() method returns -1 if the value is not found. The rfind() method is almost the same as the rindex() method.
Python String rindex() Method Python string method rindex() returns the last index where the substring str is found, or raises an exception if no such index exists, optionally restricting the search to string[beg:end].
Strings are zero-indexed: The index of a string's first character is 0 , and the index of a string's last character is the length of the string minus 1.
The lastIndexOf() method returns the last index at which a given element can be found in the array, or -1 if it is not present. The array is searched backwards, starting at fromIndex .
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...
>>> txt = '''first line ... second line ... third line''' >>> txt.rfind('\n') 22 >>> txt.rindex('\n') 22
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With