为什么rfind和find在Python 2.6.5中返回相同的值?

Avn*_*esh 8 python substring find

我对Python比较陌生,有些东西正在起作用.基本上,当我调用str.rfind("test")字符串时,输出与...相同str.find("test").我最好向您展示一个例子:

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
Run Code Online (Sandbox Code Playgroud)

根据我的理解,价值line.find是可以的,但价值line.rfind应该是9.我是否误解了这些功能或者没有很好地使用它们?

小智 24

我想你期望rfind在第一个/最左边的比赛中返回最右边角色的索引"what".它实际上返回最后/ 最右边匹配中最左边字符的索引"what".引用文档:

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

返回找到substring sub的字符串中的最高索引,以便包含subs[start:end].可选参数startend被解释为切片表示法.-1失败时返回.

"ab c ab".find("ab")会是0,因为最左边的一个出现在左端.
"ab c ab".rfind("ab")会是5,因为最右边的事件是从那个索引开始的.


小智 6

find()将返回第一个匹配的索引。但rfind将为您提供该模式的最后一次出现。如果你尝试匹配重复的匹配大小写就会很清楚。

检查这个例子
       >>> 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
Run Code Online (Sandbox Code Playgroud)