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