The find method
The find method returns the index of the first substring match in a string. In the first parameter of the method, we specify the substring we need, in the second and third optional parameters - the index of the beginning and end of the search, respectively. If the substring is not found, the method will return the number -1.
Syntax
string.find(substring, [search start index], [search end index])
Example
Let's find the substring 'a', specifying the beginning and end to search for:
txt = 'abcadea'
print(txt.find('a', 1, 4))
Result of code execution:
3
Example
Let's find the substring 'a' by changing the search indices:
txt = 'abcadea'
print(txt.find('a', 1, 3))
Result of code execution:
-1
Example
Now let's find the substring 'a' without specifying the indexes for its search:
txt = 'abcadea'
print(txt.find('a'))
Result of code execution:
0
See also
-
method
index,
which finds the index of a matching substring in a string -
method
rfind,
which returns the index of the last match of a substring in a string -
method
count,
which returns the number of occurrences of a substring in a string -
method
startswith,
which checks a substring from the beginning of a string