Python String find() method
Python String find() method
The string.find() method in Python finds the first occurrence of the specified value and returns the lowest index in the string if the substring sub is found else it returns -1 if the sub is not found.
Syntax
string.find(sub[, start[, end]])
Parameter
sub: This parameter represents the substring to be searched in the string str.
start( Optional): This parameter signifies the substring from where the search is to start and its default value is 0.
end: This parameter signifies the substring from where to end the search and its default value is the end of the string.
Return
This method returns the lowest index in the string if the substring sub is found else it returns -1 if the sub is not found.
Example 1
# Python programing explaining # the find () method # initializing the string value strVal = "How much wood would a woodchuck chuck if a woodchuck could chuck wood?\nHe would chuck, he would, as much as he could, and chuck as much wood \nAs a woodchuck would if a woodchuck could chuck wood" # will search of the substring could in the string and return the index result1 = strVal.find('could') print("The index of Substring 'could' :", result1) result2 = strVal.find('chuck') print("The index of Substring 'chuck':", result2) # How to use find() if (strVal.find('wood,') != -1): print("The substring 'wood' is present in the string.”) else: print("Doesn't contain the substring wood")
Output
The index of Substring 'could' : 53 The index of Substring 'chuck': 26 Doesn't contain the substring wood
Example 2
# Python programing explaining # the find () method # initializing the string value strVal = "Python is an easy language to learn." # will find the substring within the given start and end range. index = strVal.find("e", 5, 20) #printing the index of the substring print("The index value of first occurring 'e'(within range 5 to 20) is",index) # will return -1 if the substring if not found index= strVal.find("Z",3,10) print("The index value z is ",index)
Output
The index value of first occurring 'e'(within range 5 to 20) is 13 The index value z is -1