Python String type provides the find()
method which is used to find the first occurrence of the specified search term. If the specified search term can not be found the -1
is returned as the result. The find() method is very similar to the index()
method where the index() method raises an exception if the specified search term can not be found.
String find() Method Syntax
The String find() method has the following syntax which consists of 3 parameters where 2 parameters are optional.
STRING.find(SEARCH_TERM,START_INDEX,END_INDEX)
- SEARCH_TERM is a single more characters which will be searched inside the STRING.
- START_INDEX is the index number where the search starts. This parameter is optional. The deafult value is 0.
- END_INDEX is the index number where the search ends. This parameter is optional. The default value is end of the string.
Search String
We can search a string by providing the search term as the parameter. In the following example, we will search “python” in the string “I love the pythontect.”.
sentence = "I love the pythontect."
a = sentence.find("python")
print(a)
Search String After Specified Index
We can use the find() method in order to search the given search term after the specified index for the string. In the following example, we search after index 5.
sentence = "I love the pythontect."
a = sentence.find("python",5,len(sentence))
print(a)
Search String Before Specified Index
Also, we can search before the specified index for the given search term. We will search before index 13.
sentence = "I love the pythontect."
a = sentence.find("python",0,15)
print(a)
Search String Between Specified Indexes
We can set the start and end index in order to search given search terms between specified indexes. In the following example, we search between 5 and 15 where 5 is the start index and 15 is the end index.
sentence = "I love the pythontect."
a = sentence.find("python",5,15)
print(a)