In this section, we will learn what String find() method is and how to use it in Python.
Substring in Python: find() Method
The Python string find() method is used to search for a value in a string.
Basically, this method takes a string value as its argument and returns the position (index number) of the first occurrence where the same value was there in the target string.
Note: the value -1 will return if the target string did not have the specified value!
Python String find() Method Syntax:
string.index(value, start, end)
String find() Method Parameter
The method takes 3 arguments:
- The first argument is the string value that we want to search for in the target string.
- The second argument is the index number where we want to start the search for the specified value. This value is optional and if ignored, the value 0 will be used instead.
- The third argument is the index number where we want to stop the search for the specified value. This value is also optional and if ignored, the size of the target string value will be used instead.
String find() Method Return Value
The return value of this method is the index number where the first occurrence of the specified value is.
Note: the value -1 will return if there’s no occurrence for the specified value.
Example: python string search with find method
s1 = "They know we know that they know we know!" result = s1.find("know") print(result)
Output:
5
Example: python find substring
s1 = "They know we know that they know we know!" result = s1.find("John Doe") print(result)
Output:
-1