Tutorial Study Image

Python index()

The index() function in python helps to return the position or index of the given substring in the string. If the searched substring is not found, it will raise an exception. Here we can also provide starting and ending point of the search through the string.


cstr.index(sub[, start[, end]] ) #where start & end should be integers
 

index() Parameters:

The index() function takes three parameters. If the start and end index is not provide searching will start from zero indexes and up to the end of the string. This method is similar to the find() method, the difference is that find() will return -1 if the searched substring is not found whereas an index() method throws an exception.

Parameter Description Required / Optional
sub substring to be searched in the string str Required
start start searching from this index Optional
 end search the substring up to this index Optional

index() Return Value

The output of this method should be an integer value indicating the position of the substring. If more than one occurrence of the substring is found, it will return the first occurrence only.

Input Return Value
if substring  index of substring
if no substring ValueError exception

Examples of index() method in Python

Example 1: How index() works with substring argument only?


string = 'Python is very easy to learn.'

result = string.index('very easy')
print("Substring 'very easy':", result)

result = string.index('Php')
print("Substring 'php':", result)
 

Output:


Substring 'very easy': 10

Traceback (most recent call last):
  File "", line 6, in 
    result = string.index('Php')
ValueError: substring not found

Example 2: How index()works with start and end arguments


string = 'Python is very easy to learn.'

# Substring is searched in 'very'
print(string.index('very', 6))

# Substring is searched in 'easy '
print(string.index('easy', 5, 10))

# Substring is searched in 'to'
print(string.index('to', 15, 23))
 

Output:


10
Traceback (most recent call last):
  File "", line 7, in 
    print(quote.index('easy', 5, 10))
ValueError: substring not found
20