Python 3 – String find() Method
The find()
method in Python 3 is used to find the index of the first occurrence of a substring in a given string. It returns the index if the substring is found; otherwise, it returns -1. The find()
method is case-sensitive, which means the method distinguishes between upper and lower case letters.
string = "Hello, world!"
sub_string = "world"
print(string.find(sub_string))
Output:
7
In this example, the find()
method is used to find the index of the substring “world” in the string “Hello, world!”. Since “world” is found in the string at index 7, the find()
method returns 7.
If the substring is not found in the string, the find()
method returns -1.
string = "Hello, world!"
sub_string = "Python"
print(string.find(sub_string))
Output:
-1
In this example, the find()
method is used to find the index of the substring “Python” in the string “Hello, world!”. Since “Python” is not found in the string, the find()
method returns -1.
The find()
method also accepts two optional parameters, start
and end
. These parameters are used to specify the starting and ending indexes for the search.
string = "Hello, world!"
sub_string = "o"
print(string.find(sub_string, 5, 10))
Output:
7
In this example, the find()
method is used to find the index of the first occurrence of the substring “o” in the string “Hello, world!” between the indexes 5 and 10. The start
parameter is 5, and the end
parameter is 10. Since “o” is found in the specified range of the string at index 7, the find()
method returns 7.
If the specified range does not contain the substring, the find()
method returns -1.
string = "Hello, world!"
sub_string = "o"
print(string.find(sub_string, 2, 5))
Output:
-1
In this example, the find()
method is used to find the index of the first occurrence of the substring “o” in the string “Hello, world!” between the indexes 2 and 5. Since the specified range does not contain “o”, the find()
method returns -1.
It is also worth mentioning that the find()
method is not a substitute for regular expressions. For more complex pattern matching, it is better to use regular expressions.
Conclusion
In conclusion, the find()
method in Python 3 is a useful method for finding the index of the first occurrence of a substring in a given string. It is case-sensitive and returns -1 if the substring is not found in the string. The find()
method also accepts optional parameters start
and end
for specifying the range of the search. However, for more complex pattern matching, it is better to use regular expressions.