Python String Search: in, find() and index()
Core idea
A substring is a contiguous portion of a string. needle in text returns True or False, indicating whether it occurs. The methods text.find(needle) and text.index(needle) return the first matching position when present. A method is an operation called through a value using a dot.
label = "tea green tea"print("green" in label)print("Tea" in label)print(label.find("tea"))The search is case-sensitive. The first occurrence of tea begins at zero, even though it appears again later.
Find a missing substring
label = "tea green tea"print(label.find("green"))print(label.find("milk"))The result -1 from find is a sentinel (a special result meaning no match), not a position to read from the string. An empty needle matches at position 0 when no search bounds are supplied.
Intentional error: index without a match
Unlike find, index raises ValueError if the substring is absent. Use find if your contract calls for -1, or in if you only need a yes/no answer.
Common mistake
Never treat find() returning zero as failure. Zero is the first position. Avoid using a -1 result as an index, since negative indexing would read the final character.
Practice
In "tea:mint:tea", predict the first position of "mint" and the result of searching for "coffee".
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
String search and membership
Check your understanding of search and membership.
What is printed?
print("mint mint".find("mint"))What is printed?
print("Tea" in "tea")What happens?
print("red".index("blue"))What does a result of -1 from find mean?