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

Alan Gauld alan.gauld at btinternet.com
Mon Sep 3 01:48:49 CEST 2007


"Ricardo Aráoz" <ricaraoz at gmail.com> wrote

>>From Python 2.5 documentation :
>
> index( sub[, start[, end]])
> Like find(), but raise ValueError when the substring is not found.

As opposed to find() which returns -1 when the string is
not found. That means you can use try/except with
index but must check for -1 with find:

if 'foo'.find('q') == -1:
    print 'oops!'

as opposed to

try: 'foo'.index('q')
except ValueErrror: print 'oops!'

Which style is best will depend on what you are doing.

HTH,

Alan g




More information about the Tutor mailing list