.find()
Anonymous contributor
Published Oct 18, 2021Updated Dec 31, 2021
Contribute to Docs
The .find()
string method takes in a substring (and optionally start/end index), returns the index number of the first occurrence of the substring inside a string. It is case sensitive.
If the substring is not found, returns -1
.
Syntax
string.find(substring, start, end)
substring
: The substring to look for.start
(optional): The starting index of the string to begin the search.end
(optional): The starting index of the string to end the search.
If start
and end
index are not specified, it will default to searching the substring in the whole string. So by default, start = 0
and end = len(string)
.
Example 1
Use .find()
without specifying the start
and end
index:
new_string = "I like to eat potato"like_result = new_string.find("like")drink_result = new_string.find("drink")to_result = new_string.find("to")print(like_result) # Output: 2print(drink_result) # Output: -1print(to_result) # Output: 7
like
is found at index 2 of thenew_string
string.drink
is not found in thenew_string
string, so it’s -1.to
is found at two places in thenew_string
string, but.find()
returns the first occurrence, instead of the other occurrence at index 18.
Example 2
Use .find()
with only the start
index specified:
new_string = "I like to eat potato"like_2_result = new_string.find("like", 2)like_4_result = new_string.find("like", 4)to_5_result = new_string.find("to", 5)to_10_result = new_string.find("to", 10)print(like_2_result) # Output: 2print(like_4_result) # Output: -1print(to_5_result) # Output: 7print(to_10_result) # Output: 18
- If index starts on 2 (“l” in “like”),
like
is found at index 2. - If index starts on 4 (“k” in “like”),
like
is not found, so it’s -1. - If index starts on 5 (“e” in “like”),
to
is found at two places in thenew_string
string, but.find()
returns the first occurrence, instead of the other occurrence at index 18. - If index starts on 10 (“e” in “eat”),
to
is found at index 18.
Codebyte Example
Use .find()
with the start
and end
index specified:
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Python on Codecademy
- Skill path
Analyze Data with Python
Learn to analyze and visualize data using Python and statistics.Includes 8 CoursesWith CertificateIntermediate13 hours - Course
Learn Python 3
Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.With CertificateBeginner Friendly23 hours