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

# Find index of the substring 'Developer'
S = 'Bob is a Developer at ABC'
x = S.index('Developer')
print(x)
# Prints 9

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

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

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

# Find ‘Big’ starting a position 7
S = 'Big, Bigger, Biggest'
x = S.index('Big',7)
print(x)
# Prints 13

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

# Find ‘Big’ in between 2 & 10
S = 'Big, Bigger, Biggest'
x = S.index('Big',2,10)
print(x)
# Prints 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.

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

S = 'Bob is a Developer at ABC'
x = S.find('Manager')
print(x)
# Prints -1