Re: Use of index

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Michiel Overtoom

    Re: Use of index

    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("monste r")
    12
    >>print b.find("pasta")
    -1
    >>print b.index("pasta" )
    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(b.inde x)
    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


Working...