Saturday, December 28, 2024
Google search engine
HomeLanguagesDifference Between find( ) and index( ) in Python

Difference Between find( ) and index( ) in Python

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 = 'Lazyroar for Lazyroar'
  
# 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 = 'Lazyroar for Lazyroar'
  
# 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 found Returns -1 if substring isn’t found
It shouldn’t be used if you are not sure about the presence of the substring It 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 tuples This can only be applied to strings
It cannot be used with conditional statement It can be used with conditional statement to execute a statement if a substring is found as well if it is not
RELATED ARTICLES

Most Popular

Recent Comments