What is the difference between String find() and index() method?

Overview

Python provides the following two built-in methods to find the first occurrence of a given substring in a string:

  • find()

  • index()

Both methods have the same syntax. However, in the case where the required substring is not found in the target string, there is a significant difference in the output of both these methods:

  • find() returns -1.

  • index() raises an exception.

find()

Syntax

string_name.find(str, start, end)

Code sample

string = 'Educative shot'
# starts search at index 1 and ends at index 7
print(string.find('ca ', 1, 7))

Note: In the code above, the substring ca has a space after the character a. That’s why the method find() returns -1.

index()

Syntax

string_name.find(str, start, end)

Code sample

txt = "Hello, welcome to Educative."
# Substring to be search
x = txt.index("b")
# display the position
print(x)

Note: In the code above, a ValueError is raised since substring b is not found in the string.

Free Resources