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 7print(string.find('ca ', 1, 7))
Note: In the code above, the substring
cahas a space after the charactera. That’s why the methodfind()returns -1.
index()
Syntax
string_name.find(str, start, end)
Code sample
txt = "Hello, welcome to Educative."# Substring to be searchx = txt.index("b")# display the positionprint(x)
Note: In the code above, a
ValueErroris raised since substringbis not found in the string.