I'm relatively new to Python, and something is acting up. Basically, when I call str.rfind("test")
on a string, the output is the same as str.find("test")
. It's best that I show you an example:
Python 2.6.5 (r265:79063, May 6 2011, 17:25:59)
[GCC 4.5.0 20100604 [gcc-4_5-branch revision 160292]] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import string
>>> line = "hello what's up"
>>> line.rfind("what")
6
>>> line.find("what")
6
By my understanding, the value of line.find
is okay, but the value of line.rfind
should be 9
. Am I misinterpreting these functions or not using them well?
Python String rfind() method returns the rightmost index of the substring if found in the given string. If not found then it returns -1.
Difference between find() and rfind() The Python function rfind() is similar to the find() function, with the sole difference being that rfind() returns the highest index (from the right) for the provided substring, whereas find() returns the index position of the element's first occurrence, i.e. the very first index.
rfind() method returns an integer value. If substring exists inside the string, it returns the highest index where substring is found. If substring doesn't exist inside the string, it returns -1.
rindex() method is similar to rfind() method for strings. The only difference is that rfind() returns -1 if the substring is not found, whereas rindex() throws an exception.
find() will return the index of the first match. But rfind will give you the last occurence of the pattern. It will be clear if you try to match repeated match case.
check this Example >>> string='hey! how are you harish'
>>>string.find('h')
>>>0 #it matched for first 'h' in the string
>>> string.rfind('h')
22 #it matched for the last 'h' in the string
I think you're expecting rfind
to return the index of the rightmost character in the first/leftmost match for "what"
. It actually returns the index of the leftmost character in the last/rightmost match for "what
". To quote the documentation:
str.rfind(sub[, start[, end]])
Return the highest index in the string where substring sub is found, such that sub is contained within
s[start:end]
. Optional arguments start and end are interpreted as in slice notation. Return-1
on failure.
"ab c ab".find("ab")
would be 0
, because the leftmost occurrence is on the left end."ab c ab".rfind("ab")
would be 5
, because the rightmost occurrence is starts at that index.
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