Open In App

Difference Between find() and index() in Python

Last Updated : 21 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Both methods are used to locate the position of a substring within a string but the major difference between find() and index() methods in Python is how they handle cases when the substring is not found. The find() method returns -1 in such cases, while index() method raises a ValueError.

Example of find()

Python
s = "hello world"

# Finds the position of the substring "world"
print(s.find("world"))

# Returns -1 when substring is not found
print(s.find("python"))

# Finds the position of "o" starting from index 5
print(s.find("o", 5))

Output
6
-1
7

Explanation:

  • s.find("world") returns 6 because the substring "world" starts at index 6.
  • s.find("python") returns -1 as substring "python" is not present in string.
  • s.find("o", 5) starts the search from index 5 and finds the first occurrence of "o" at index 7.

Example of index()

Python
s = "hello world"

# Finds position of the substring "world"
print(s.index("world"))

# Raises a ValueError when substring is not found
print(s.index("python"))

# Finds position of "o" starting from index 5
print(s.index("o", 5))
6

ERROR!
Traceback (most recent call last):
  File "<main.py>", line 7, in <module>
ValueError: substring not found

Explanation:

  • s.index("world") returns 6 because substring "world" starts at index 6.
  • When s.index("python") is executed then it raises a ValueError as the substring "python" is not in string.
  • s.index("o", 5) starts searching from index 5 and finds the first occurrence of "o" at index 7.

When to use find() and index()?

  • Use find() when we need to check if a substring exists and do not want to handle exceptions.
  • Use index() when we are sure that the substring exists or we want an exception to be raised if it doesn't exist.

Practice Tags :

Similar Reads

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy