Why do rfind and find return the same values ​​in Python 2.6.5?

I am relatively new to Python and something is working. Basically, when I call str.rfind("test") on a line, the output is the same as str.find("test") . It is best to 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 up" >>> line.rfind("what") 6 >>> line.find("what") 6 

In my opinion, the value of line.find is fine, but the value of line.rfind should be 9 . Am I misinterpreting these functions or not using them well?

+7
source share
3 answers

I think you expect rfind return the index of the rightmost character in the first / left match for "what" . It actually returns the index of the leftmost character in the last / right match for "what ". To quote the documentation :

str.rfind(sub[, start[, end]])

Returns the highest index in the string where the substring is sub, so sub is contained in s[start:end] . The additional arguments start and end are interpreted as in slice notation. Return -1 on failure.

"ab c ab".find("ab") will be 0 because the leftmost occurrence is on the left end.
"ab c ab".rfind("ab") will be 5 because the rightmost occurrence begins with this index.

+19
source

To understand what .rfind , try your example with a line like β€œhello, what, hello what” (that is, more than one occurrence of β€œwhat”)

+2
source

find () will return the index of the first match. But rfind will give you the latest appearance of the template. It will be clear if you try to match the case of re-matching.

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 
+1
source

All Articles