Member-only story

Understanding the Difference Between find() and index() in Python

Allwin Raju
2 min readDec 21, 2024

--

Photo by Hitesh Choudhary on Unsplash

When working with strings in Python, locating a substring is a common task. Python provides two built-in methods to achieve this: find() and index(). While they might seem similar at first glance, they have distinct behaviours that suit different use cases. In this post, we’ll explore the differences between these methods and when to use each one.

Read for free: https://allwin-raju.medium.com/understanding-the-difference-between-find-and-index-in-python-365afe069dec?sk=b1fd214627f8d276cba85a4378e6b5e0

1. The find() Method

The find() method searches for a substring within a string and returns the index of the first occurrence. If the substring is not found, it returns -1. This makes find() a safe option when you’re unsure if the substring exists.

Syntax:

string.find(substring, start, end)
  • substring: The string you want to search for.
  • start (optional): The position to begin the search.
  • end (optional): The position to end the search.

Example:

text = "hello world"

# Substring exists
result = text.find("world")
print(result) # Output: 6

# Substring does not exist
result =…

--

--

No responses yet