Python String index() Method With Example

Python String Index

Now, we are going to learn about the index method. Using the index method, we are going to get the first occurrence of the specified string in the given string. This is like finding where the string ‘a’ occurred first in the string ‘GyaniPandit’. The answer would be 2. Let’s have a look at a program, which tries to explain the same thing.

Python String index() Method

As you can see, we have a string here, and we are trying to find the first occurrence of the string ‘welcome’ in the specified string. The output that we get in this case, is 10 since the string ‘welcome’ first occurs starting from the index 10.

Now, you might be wondering if the find method in relation to the string does the same thing. It also returns the first occurrence index of the string in the specified string. But then what is the difference? Well, the difference lies in the situation, when we try to find the first occurrence index of some string that is not there in the given string. In this situation, the find method returns -1, and the index method raises an exception (ValueError).

Let’s have a look at a simple program, which tries to demonstrate the same thing.

As you can see that we have a string, and then we are trying to use the index method, and we pass such a string, which is not there in the string. In such a situation, the index method is going to give an error. You can try executing the program and observing the output.

Also, we can provide the start and end as optional arguments to the index method.  This is like we are searching for the first occurrence of some string in the given range. For example, we can use the index method to get the first occurrence of the string ‘python’, in the string ‘python is a snake, and python is a programming language’, in the range of 7 to 29. Let’s have a look at the program, which tries to demonstrate the same.

As you can see in the above program, we have a string, and then we are trying to get the first occurrence of the string ‘python’ in the given string, in the given range. You can try executing the program and then observe the output as well.

So, as and when required, we can make use of the index method, which returns the first occurrence index of some string in the given string. If the string is not there in the given string, then it raises an error.