Difference Between find() and index() in Python (original) (raw)

Last Updated : 21 Nov, 2024

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))

`

**Explanation:

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 ValueError: substring not found

**Explanation:

When to use find() and index()?

Similar Reads