Use of index
Michiel Overtoom
motoom at xs4all.nl
Sat Jul 12 08:45:53 EDT 2008
SUBHABRATA wrote...
> 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
True
>>> print b.find("monster")
12
>>> print b.index("monster")
12
>>> print b.find("pasta")
-1
>>> 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:
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:
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,
Greetings
--
"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
http://www.catb.org/~esr/halloween/halloween4.html
More information about the Python-list
mailing list