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

Varsha Purohit varsha.purohit at gmail.com
Mon Sep 3 01:48:56 CEST 2007


 Thanks guys it was really helpful.... i m just a beginner in python start
to program since two days back. So finding little difficulty with some
concepts.

On 9/2/07, Ricardo Aráoz <ricaraoz at gmail.com> wrote:
>
> 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
>
>


-- 
Varsha Purohit,
Graduate Student,
San Diego State University
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070902/4ab34417/attachment.htm 


More information about the Tutor mailing list