SUBHABRATA wrote...
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:
True
12
12
-1
Traceback (most recent call last):
File "<pyshell#1 8>", line 1, in <module>
print b.index("pasta" )
ValueError: substring not found
This is also documented in the built-in help:
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 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
Now, my q is can we use index like find?
'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 "monster" in b
>>print b.find("monster ")
>>print b.index("monste r")
>>print b.find("pasta")
>>print b.index("pasta" )
File "<pyshell#1 8>", line 1, in <module>
print b.index("pasta" )
ValueError: substring not found
>>>
This is also documented in the built-in help:
>>help(b.inde x)
index(...)
S.index(sub [,start [,end]]) -int
Like S.find() but raise ValueError when the substring is not found.
>>help(b.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