Python - String index() Method


Advertisements

The string index() method is used to find out the index number for first occurrence of specified character(s) in the given string. This method is very similar to find() method. Only difference is that find() method returns -1 when character(s) is not found in the string and index() method gives exception error.

This method has two optional parameters also which can be used to specify starting point and end point within the string for this operation. Default values are start and end of the string.

Syntax


string.index(value, start, end)

Parameters

value Required. value of the character(s) which need to be searched in the string.
start Optional. An integer specifying start position of search. default value is 0.
end Optional. An integer specifying end position of search. default value is end of the string.

Example: index() method when value is present

In the below example, index() method to used to find out the index number for first occurrence of specified character(s) in the given string.

MyString = "Python is a programming language and learning Python is fun."
print(MyString.index("Python"))

print(MyString.index("Python", 40, 55))

Output

0

46

Example: index() method when value is not present

The index() method raises exception when the specified character(s) is not present in the string.

MyString = "Python is a programming language and learning Python is fun."
print(MyString.index("Python", 10, 20))

Output

ValueError: substring not found

String Methods
Advertisements