Python string Method - find()
The find()
method in Python strings is used to search for a substring in a given string and returns the index of the first occurrence of the substring. If the substring is not found in the string, it returns -1
.
The syntax for the find()
method is as follows:
string.find(substring, start, end)Source:www.theitroad.com
Here, string
is the string that we want to search in, substring
is the substring that we want to find, start
is an optional integer argument that specifies the starting index of the search (default is 0
), and end
is an optional integer argument that specifies the ending index of the search (default is the length of the string).
Example:
# Defining a string my_string = "hello world" # Using the find() method result = my_string.find("world") print(result) # Output: 6
In the above example, the find()
method is used to search for the substring "world"
in the string "hello world"
. Since "world"
occurs in the string starting at index 6
, the find()
method returns 6
, which is then assigned to the variable result
. The output of the program is 6
.
If the substring is not found in the string, the find()
method returns -1
. For example:
# Using the find() method with a substring that does not occur in the string result = my_string.find("python") print(result) # Output: -1
In this example, the substring "python"
does not occur in the string "hello world"
, so the find()
method returns -1
.