In Python, find() searches for a substring and returns the index of the first match. If the text is missing, it returns -1.
sub is required. Optional start and end limit the search to a slice. The search is case-sensitive.
Syntax
Call find with the substring. Start with this line.
python
pos = text.find("Python")
Call
What it does
"hello".find("ll")
Returns 2.
"hello".find("x")
Returns -1 when missing.
Do not write if text.find(sub): — index 0 is falsy. Use != -1.
Library declarations
python
str.find(sub[, start[, end]]) → int
Parameters
Parameter
Description
sub
Required. The substring to search for.
start
Optional. Index where the search starts. Default 0.
end
Optional. Exclusive end index of the search range.
Return Value
Return Value
Description
int
First match index, or -1 if not found.
Python Examples
Example 1 — Find a Substring Index
Get the first match position, or -1 when it is missing.
python
text = "CodeToFun"
print(text.find("To"))
print(text.find("Java"))
print(text.find("o")) # first "o" only
Output
4
-1
1
How It Works
Match "To". Starts at index 4 in "CodeToFun".
Missing text."Java" is not present → -1.
First only. There are two "o" letters; find returns the first (1).
Safe check. Compare with != -1 when presence matters.
Example 2 — Limit Search with start / end
Search inside a slice without creating a new string first.
python
text = "one two two three"
print(text.find("two")) # first "two"
print(text.find("two", 5)) # start after the first
print(text.find("two", 0, 5)) # only look in text[0:5]
Output
4
8
-1
How It Works
Default search. First "two" begins at index 4.
Raise the start. From index 5, the next match is at 8.
Cap the end. In text[0:5] there is no full "two" → -1.
Slice semantics.start/end behave like slicing bounds.
Example 3 — find() vs index()
Same success path; different failure behavior.
python
text = "Python"
print("find:", text.find("Java"))
try:
print("index:", text.index("Java"))
except ValueError as err:
print("index error:", err)
Output
find: -1
index error: substring not found
How It Works
find stays quiet. Missing text → -1.
index raises. Same miss becomes a ValueError.
Pick by intent. Optional match → find; required match → index.
Catch when needed. Wrap index in try/except if absence is possible.
Frequently Asked Questions
It returns the first index of a substring, or -1 if missing.
find() returns -1. It does not raise.
Yes. Fold both sides with casefold() for case-insensitive search.
find() returns -1 when missing. index() raises ValueError.