Python String index() Method

Searches the string for a given substring

Usage

The index() method searches for the first occurrence of the specified substring sub and returns its index.

If specified substring is not found, it raises ValueError exception.

The optional arguments start and end are used to limit the search to a particular portion of the string.

Syntax

string.index(sub,start,end)

Python string index() method parameters
ParameterConditionDescription
subRequiredAny string you want to search for
startOptionalAn index specifying where to start the search.
Default is 0.
endOptionalAn index specifying where to stop the search.
Default is the end of the string.

Basic Examples

Example: Find index of the substring ‘Developer’

S = 'Bob is a Developer at ABC'
x = S.index('Developer')
print(x)    # 9

index() method raises ValueError exception, if specified substring is not found in the string.

Example: Find index of the substring ‘Manager’

# ValueError: substring not found
S = 'Bob is a Developer at ABC'
x = S.index('Manager')
print(x)

If you want to search the string from the middle, specify the start parameter.

Example: Find ‘Big’ starting a position 7

S = 'Big, Bigger, Biggest'
x = S.index('Big',7)
print(x)    # 13

You can also specify where to stop the index() search with end parameter.

Example: Find ‘Big’ in between 2 & 10

S = 'Big, Bigger, Biggest'
x = S.index('Big',2,10)
print(x)    # 5

index() vs find()

The index() method is identical to the find() method.

The only difference is that the find() method returns -1 (instead of raising a ValueError), if the substring is not found.

Example:

# ValueError: substring not found
S = 'Bob is a Developer at ABC'
x = S.index('Manager')
print(x)
S = 'Bob is a Developer at ABC'
x = S.find('Manager')
print(x)    # -1