Skip to content
Related Articles

Related Articles

Difference Between find( ) and index( ) in Python
  • Last Updated : 24 Jan, 2021

In Python, to find the index of a substring in a string can be located by python’s in-built function using find() or index(). Both of them return the starting index of the substring in a string if it exists. This article discusses which one to use when and why.

index() function

The index() method returns the index of a substring or char inside the string (if found). If the substring or char is not found, it raises an exception.

Syntax:

string.index(<substring>)

Example:

Python3




string = 'geeks for geeks'
  
# returns index value
result = string.index('for')
print("Substring for:", result)
  
result3 = string.index("best")
print("substring best:", result3)

Output:



Substring for: 6

Traceback (most recent call last):

 File “<string>”, line 8, in <module>

ValueError: substring not found

find() method

The find() method returns the index of first occurrence of the substring or char (if found). If not found, it returns -1.

Syntax:

string.find(<substring>)

Example:

Python3




string = 'geeks for geeks'
  
# returns index value
result = string.find('for')
print("Substring for:", result)
  
result = string.find('best')
print("Substring best:", result)

Output:

Substring for: 6

Substring best: -1

Table of Difference Between index() vs find()

index()find()
Returns an exception if substring isn’t foundReturns -1 if substring isn’t found
It shouldn’t be used if you are not sure about the presence of the substringIt is the correct function to use when you are not sure about the presence of a substring
This can be applied to strings, lists and tuplesThis can only be applied to strings
It cannot be used with conditional statementIt can be used with conditional statement to execute a statement if a substring is found as well if it is not

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :