Index() Method Of Str Class

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:

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:

The substring 'children' was found at position:24

The substring 'Earth' was found at position:4

 


Copyright 2023 © pythontic.com