开发者

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

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.
&g开发者_开发知识库t;>> 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?


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.


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


To understand better what .rfind is meant for, try your example with a string like "hello what's up, hello what's up" (that is, more than 1 occurrence of "what")

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜