index() method of str class

The index() method of str class returns the lowest position of the substring. If the index is not found it raises an exception of type ValueError

Str Updated 10 Mar 2017 1 min read

Method Name

index

Method Signature

index(sub[, start[, end]])

Method Overview

  • The index method returns the lowest index at which a substring is found.

  • Start and End indexes can be specified for searching the substring.

  • Behavior of the index() method is same as find() but index() raises an exception of type ValueError when the substring is not found in the string.

Example

python
quote   = "All grown-ups were once children"

substr  = "children"

pos     = quote.index(substr)

print("The substring '{}' was found at position:{}".format(substr,pos))

quote       = "The Earth is not just an ordinary planet"

substr      = "Earth"

startPos    = 3

endPos      = len(quote)

# search the substring with the start and stop positions specified

pos     = quote.index(substr, startPos, endPos)

print("The substring '{}' was found at position:{}".format(substr,pos))

Output

Output
The substring 'children' was found at position:24

The substring 'Earth' was found at position:4