Skip to main content

index()

The index() method in Python is a string method used to find the index of a substring within a string. It returns the index of the first occurrence of the specified substring in the string. If the substring is not found, it raises a ValueError.

Parameter Values

Parameter Description
sub

The substring to search for in the string.

start

The index in the string at which to begin the search.

end

The index in the string at which to end the search.

Return Values

The index() method in Python returns an int indicating the position of a substring.

How to Use index() in Python

Example 1:

The index() method finds the first occurrence of a substring in a string and returns its index. It raises a ValueError if the substring is not found.

sentence = 'This is a sample sentence' 
index = sentence.index('sample') 
print(index) # Output: 10
Example 2:

The index() method can take additional arguments like start and end index for searching within a specific portion of the string.

sentence = 'This is a sample sentence' 
index = sentence.index('s', 8) 
print(index) # Output: 10
Example 3:

If the substring is not found, the index() method raises a ValueError. You can handle this using a try-except block.

sentence = 'This is a sample sentence' 
try: 
    index = sentence.index('notfound') 
    print(index) 
except ValueError: 
    print('Substring not found') # Output: Substring not found