Python provides find()
function in string variable types in order to find the specified term or string. The find()
function will return the first occurrence of the given search term position in the given string. If the given search term is not found the find()
method will return -1
in order to express nothing found.
find() Function Syntax
The find()
method has the following syntax. It can accept up to 3 parameters where two of them are optional which means they can be omitted.
STRING.find(VALUE, START, END)
- `STRING` is the variable name where the text or string is stored which will be searched.
- `VALUE` is the value, string or term which will be searched in the STRING.
- `START` is optional and used to set the search start position in the STRING.
- `END` is optional and used to set the search end position in the STRING.
Find Given String
We will search with a simple example where we will search the given term in the given string. In this example we will search the termpoftut.com
in the string I love poftut.com
.
str="I love poftut.com" match = str.find("poftut.com") print(match) # The output will be 7 match = str.find("POFTUT.COM") print(match) # The output will be -1

We can see the start index of the poftut.com
is 7 in the I love poftut.com
where POFTUT.COM
can not be found in the given string. Because find()
function search in a case sensitive manner so the search will return -1
in order to express there is not match.
Find String From Specified Position To End
Alternatively, we can specify the start position of the search where the given term will be searched from the given start position or index. The start position or index will be provided as the second argument to the find()
method after the search term. In this following example, we will search the term poftut.com
in the I love poftut.com
by starting the search from different index numbers.
str="I love poftut.com" match = str.find("poftut.com",3) print(match) #The output will be 7 match = str.find("poftut.com",9) print(match) #The output will be -1

Find String From Start To Specified Position
In the previous example, we set the positions of the search. We can also set the end positions of the search. In this example, we will set 10 as the end index number of the search. We will also specify the start as 0 index number.
str="I love poftut.com" match = str.find("poftut.com",0,10) print(match) #The output will be -1 match = str.find("poftut.com",0,20) print(match) #The output will be 7

We can see that when we set the search end index as 10 the poftut.com
term can not be found. If we set the end index or position as 20 the poftut.com
found at index number 7.
Find String Between Specified Positions (Start and End)
We can explicitly specify the start and end index numbers for the search. We will provide them as second and third arguments to the find()
function.
str="I love poftut.com" match = str.find("poftut.com",3,20) print(match) 7 match = str.find("poftut.com",12,20) print(match) -1
