find() method in Python String can be used to find a given substring in an original string, this method returns the first occurrence of the sub string from the beginning of the main string.
The find() method returns -1 if the sub string is not found in the original string.
Syntax
mainstring.find(substring, beginning, ending)
substring : String that we want to search in original string.
If beginning and ending points are not specified, then a substring will be searched in complete string.
s1 = "Python loves me. I love Python."
s2 = "Python"
s3 = "love"
s4 = "NodeJS"
ind1 = s1.find(s2, 0, len(s1)) # checking if s2 string is present in s1
ind2 = s1.find(s3, 0, len(s1)) # checking if s3 string is present in s1
ind3 = s1.find(s4, 0, len(s1)) # checking if s4 string is present in s1
print("ind1 :", ind1)
print("ind2 :", ind2)
print("ind3 :", ind3)
O/P
ind1 : 0
ind2 : 7
ind3 : -1
Let’s try to understand what happened in the above code :
We tried to search substrings (s2, s3, s4) in main string(s1), we were able to find the first occurrence of that particular sequence. In the third case, we got -1 as the given substring is not present in original string.
We can also search a single character in the original string.
s1 = "Python loves me. I love Python."
s2 = "n"
ind1 = s1.find(s2)
print("ind1 :", ind1)
Above code prints 5 as output.
