[Tutor] [tutor] Difference between index and find in manipulating strings

Ricardo Aráoz ricaraoz at gmail.com
Mon Sep 3 01:03:42 CEST 2007


Varsha Purohit wrote:
> Hello,
>   i have again very basic question in python string management.
> 
> I am not able to understand how find and index works and what do they
> actually return.
> 
>>>> line = "this is varsha"
>>>> print line.find("is")
> 2
>>>> print line.rfind("is")
> 5
>>>> print line.rfind("varsha")
> 8
>>>> print line.index("varsha")
> 8
> 
> what does 2 in first line signifies... and why rfind gave 5 as an output...
> 
> can anybody pls explain me what exactly is interpreter tryin to return.....
> 
Sure.
The 2 in first line means the string 'is' begins in line[2] that would
be the 'is' in 'this' (remember line's first character 't' is line[0]).
OTOH rfind looks for the first appearance of 'is' in line but starting
from the right, that would be the word 'is' which starts at line[5].
As there is only one occurrence of 'varsha' in line both methods, find
and rfind will give the same answer : 8.

>From Python 2.5 documentation :

index( sub[, start[, end]])
Like find(), but raise ValueError when the substring is not found.



HTH



More information about the Tutor mailing list