Python String index()
index() method is used to return the index of a substring if it is found inside a string.
In case if the substring is not there inside the string then this method raises an exception.
This method basically returns the index of the first occurrence of the value we are searching in a string.
In the case of non-existence of substring inside a string
ValueError Exception is raised.
Below we have a basic syntax of String
index() in Python:
string.index(value, start, end)
Given below is a description of Parameters of
index() as there are three parameters:
This is a required parameter and is used to specify the value which is to be searched.
This is an optional parameter and is used to specify where the search starts; its default value is 0.
This is an optional parameter used to specify where to end the search. The default value is to the end of the string.
index(): Returned Values
The values returned by this method are as follows:
index(): Basic Example
Below we have an example to show the working of String
ab = 'We can do whatever we want'
sample = ab.index('w', 5, 20)
The output of the above is given below:
find() vs Python String
Both these methods are same but there is a major difference in case if the substring does not exist in the string:
If we use the python
find() method then it will return
On the other hand, if we are using the python
index() then it will raise
index(): Example of value not existing inside the string
Below we have a case where we are looking for the index of a value that does not exist inside the string. Let us see the code snippet with its output:
abc = 'We can do whatever we want'
Given below is the output
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
ValueError: substring not found
index(): Without Using start and end Parameter
Below we have an example where we have not specified the value of start and end parameters of index() method. The code snippet is given below:
ab = 'Expecto Patronum'
data = ab.index('num')
Time For Live Example!
Now let us see the live example given below for
In this tutorial, we learned
index() method of Strings in Python which is used to return the index of the substring if found. We saw its parameters and a few basic examples; we also differentiate it with
find() method of strings further followed by a live example.