Difference between index() and find() in Python

Difference between index() and find() in Python

Difference between index() and find() in Python

If you want to find the substring or character in the string, there are two methods- index() and find().

Both of these methods return the index of the substring if the substring you want to search is present in the given string.

Python interview questions and answers

Example of index() and find() method

Write a program to find the index of the substring in the given string.

Example of index()

samp_str = "CSEstack programmer"
print(samp_str.index('stack'))

Output:

3

Note: The index() method can also be used to search the element in the Python list.

Example of find()

We will use the same string and sub-string for find() method.

samp_str = "CSEstack programmer"
print(samp_str.find('stack'))

Output

3

You will find the same output result.

Is there any difference between index() and find()?

Obviously, if these are two methods, there should have some differences.

Difference between index() and find() in Python

Let’s search for the sub-string which is not present in the given string.

In the given example, we are searching ‘stock’ instead of ‘stack’ in the given string.

Using index() method

samp_str = "CSEstack programmer"
print(samp_str.index('stock'))

Output:

print(samp_str.index('stock')) ValueError: substring not found

This throws an ValueError.

Getting runtime error crashes your application. This is not a good practice of coding. You have to handle this exception gracefully.

Either you can handle this exception using try-except block or using find() method.

How method() is different from index()?

Let’s see.

Using find() method

We are using same string and sub-string.

samp_str = "CSEstack programmer"
print(samp_str.find('stock'))

Output:

-1

When you use find() method to search the substring which is not present in the given string, it returns -1.

When to use index() and find()?

  • If you are sure about the presence of a substring in the given string, you can use either methods.
  • If you are not sure (substring may or may not be present in the given string), use find().
  • In case, you are using the index() method to find the index of the substring, use exception handling to avoid runtime crashes.

Related Python Programming Questions:

Hope this guide helps you to find the difference between index() and find() in Python. Use them wisely. If you have any doubt, comment below.

Happy Pythoning!

Leave a Reply

Your email address will not be published. Required fields are marked *