Menu Close

Python String index() Method

Python string index() method

Here we are going to learn about the Python string index method. The string index() function returns the first index of the first occurrence of the matching.
In this string method tutorial, we have seen various examples to understand the Python string index() method.

Python string index() method:

Python string index method is a built-in method that is used to return the index number for the first occurrence of the specified value otherwise raise an exception.

Python string find() method and index() method work the same, The only difference between these two methods is, find() method return -1 if the specified value not found in the string and the index() method raise ValueError.


The syntax of index function in Python is:-

string.index(value, start, stop)


index function in Python support three parameters.

value– ( Required ) The value search for.
start:- Optional. Where to start the search. The default index is 0.
stop:- Optional. Where to end the search. The default is to end of the string.

Return Type:

It returns index number for first occurrence of the specified value otherwise raise exception.

Let’s see an example of using the python string index function.

Python string index() method example:

Here we will take some example to understand index function in Python.

Example 1:

In this example we will use python string index method without start and end parameter.

str = "Programming Funda"
str2 = str.index('mm')

Output will be:- 6

Example 2:

In this example we will use start parameter.

str = "Programming Funda"
str2 = str.index('gramming', 2)

Output will be:- 3

Example 3:

Let’s see what happen, If the specify value not matching to the string.

str = "Programming Funda"
str2 = str.index('mg')


Traceback (most recent call last):
  File "C:\Users\user1\Desktop\tuts\jQuery\", line 2, in <module>
    str2 = str.index('mg')
ValueError: substring not found


In this tutorial, you have learned the Python string index() method to find the index number for the first occurrence of the specified value.
I hope this tutorial will have the help you. If you like this article, please share with your friends who want to learn Python programming from scratch to advanced.

For More Information:- Click Here

Previous Article
Next Article

Was this post helpful?

Related Posts

Leave a Reply