A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/python/difference-between-find-and-index-in-python/ below:

Difference Between find() and index() in Python

Difference Between find() and index() in Python

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

Explanation:

When to use find() and index()?

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4