Use of index

Michiel Overtoom motoom at
Sat Jul 12 14:45:53 CEST 2008


> Now, my q is can we use index like find?

Yes, you can.  There is only a difference when the string is not found: the
'find()' function will return -1, whereas 'index()' function will raise a
ValueError exception.

For example:

>>> b="A spaghetti monster is always great"
>>> print "monster" in b
>>> print b.find("monster")
>>> print b.index("monster")
>>> print b.find("pasta")
>>> print b.index("pasta")
Traceback (most recent call last):
  File "<pyshell#18>", line 1, in <module>
    print b.index("pasta")
ValueError: substring not found

This is also documented in the built-in help:

>>> help(b.index)
Help on built-in function index:

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

>>> help(b.find)
Help on built-in function find:

    S.find(sub [,start [,end]]) -> int
    Return the lowest index in S 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.

Hope this helps,


"The ability of the OSS process to collect and harness
the collective IQ of thousands of individuals across
the Internet is simply amazing." - Vinod Vallopillil

More information about the Python-list mailing list