Quick Reach
Python String find method
Python provides the find() method to search in a given string. The Python string find method searches through the whole string, by default, to search for given characters or word and returns the index of the first occurrence.
The Python find method also allows to specify from where to start and end the search within the string.
Let us first look at its syntax which is followed by a few examples.
How to use the find() method
Following is the general syntax of using the find Python method:
String_to_search.find(string, start, end)
where
- string_to_search is the string that you want to check if that string contains it or not?
- The String in the brackets is the search term.
- Start: It tells where should searching start in the given string.
- End: specifies where should it end searching in the string.
Note that, If the string does not contain the search term, it will return -1.
Python String find method example
The following example checks whether the given string contains the search term by using the find() method.
1
2
3
4
5
|
strToSearch = “This is Python Tutorial, and this is string find method”;
StrSearchTerm = “string”;
print (strToSearch.find(StrSearchTerm))
|
The output will be
37
What if the search term is not found?
The following example shows what happens if the search term is not found in the given string while using the Python find method. For that, a variable is given a value that does not exist in the search string. See what happens.
1
2
3
4
5
|
strToSearch = “This is Python Tutorial, and this is string find method”;
StrSearchTerm = “not”;
print (strToSearch.find(StrSearchTerm))
|
The output:
-1
Check whether string contains: with start and end number
This example shows how you can use the start and end parameters to specify where to start and end the search.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
|
strToSearch = “This is Python Tutorial, and this is string find method”;
StrSearchTerm = “Tutorial”;
search1=strToSearch.find(StrSearchTerm,1,30)
search2=strToSearch.find(StrSearchTerm,20,45)
search3=strToSearch.find(StrSearchTerm,10,20)
#Checking search 1
if search1 == –1:
print (“Tutorial is not found between 1 to 30 characters!”)
else:
print (“Tutorial starts at:” , search1)
#Checking search 2
if search2 == –1:
print (“Tutorial is not found between 20 to 45 characters!”)
else:
print (“Tutorial starts at” , search2)
#Checking search 3
if search3 == –1:
print (“Tutorial is not found between 10 to 20 characters!”)
else:
print (“Tutorial starts at” , search3)
|
The output will be:
Tutorial starts at: 15
Tutorial is not found between 20 to 45 characters!
Tutorial is not found between 10 to 20 characters!
Useful reading – String Split method | Python replace method
Leave A Comment?