Python string find() method is used to find the first occurrence of the substring.
Syntax
string.find(value, start, end)
Parameters
- value(required): It is the value we are searching for.
- start(optional): It is the index at which the method starts searching.
- end(optional): It is the index at which the method stops searching.
If the start and end indexes are not provided, then by default, it takes 0 and length -1 as starting and ending indexes where the ending indexes are not included in our search.
Return value
If the substring exists inside the string, it returns the index of the first occurrence of the substring. If the substring doesn’t exist inside the string, it returns -1.
Visual Representation
Example 1: How to Use String find() Method
line = 'Leo Messi'
index = line.find('Messi')
print(index)
Output
4
Example 2: Finding the first occurrence between specified positions
line = 'Leo Messi'
index = line.find('e', 0, 5)
print(index)
Output
1
Example 3: Finding a character that does not exist
line = 'Leo Messi'
index = line.find('a')
print(index)
Output
-1