The find() method searches a string for a substring and returns the index of the first match. Unlike index(), it returns -1 when nothing is found—so you can search safely without try/except blocks. It is one of the most-used methods for locating text inside strings.
01
Find Index
Locate first occurrence.
02
Returns int
Index or -1 if missing.
03
start / end
Limit search to a slice.
04
Case-Sensitive
A ≠ a in matching.
05
Zero-Based
First char is index 0.
06
vs index()
-1 vs ValueError.
Fundamentals
Definition and Usage
In Python, find() scans a string from left to right looking for a substring. When it finds a match, it returns the starting index (counting from 0). For example, in "Hello, World!", the substring "World" starts at index 7. If the substring does not appear, find() returns -1.
💡
Beginner Tip
Use if text.find(sub) != -1: to check existence, or compare directly: if text.find(sub) >= 0:. For a simple True/False check without needing the index, sub in text is often clearer.
Foundation
📝 Syntax
The find() method accepts one required and two optional parameters:
python
string.find(sub, start, end)
Syntax Rules
sub — the substring to search for (required).
start — optional start index; search begins here (default 0).
end — optional end index; search stops before this position.
Return value — integer index of first match, or -1 if not found.
Read-only — the original string is never modified.
Cheat Sheet
⚡ Quick Reference
Expression
Result
"Hello, World!".find("World")
7
"Hello, World!".find("Python")
-1 (not found)
"banana".find("na")
2 (first match)
"banana".find("na", 3)
4 (search from index 3)
"ABC".find("b")
-1 (case-sensitive)
Basic
text.find("error")
Index or -1
Slice
text.find("at", 5, 20)
Search in range
Check
text.find(sub) >= 0
True if found
Extract
idx = text.find("@")
Then slice text
Hands-On
Examples Gallery
Run these examples in any Python 3 interpreter. Indices start at 0 unless noted.
📚 Getting Started
Find the index of a substring in a greeting string.
Example 1 — Basic find()
Locate where "World" begins inside "Hello, World!".
python
text = "Hello, World!"
index = text.find("World")
print("Text: ", text)
print("Index:", index)
print("Char: ", text[index])
📤 Output:
Text: Hello, World!
Index: 7
Char: W
How It Works
Indices 0–6 are "Hello, "; index 7 is where "World" starts.
find() returns the index of the first character of the match.
You can use that index to slice or inspect the matched text.
Example 2 — Substring Not Found
When the substring is absent, find() returns -1.
python
text = "Hello, World!"
index = text.find("Python")
if index == -1:
print("'Python' was not found.")
else:
print("Found at index:", index)
📤 Output:
'Python' was not found.
How It Works
Always check for -1 before using the index in slicing. Accessing text[-1] would get the last character, not mean “not found”!
📈 Practical Patterns
Slice limits, case rules, and comparison with index().
Example 3 — Using start and end
Search only within part of the string by passing slice boundaries.
python
text = "Hello, Hello, World!"
first = text.find("Hello")
second = text.find("Hello", 7, 15)
print("First Hello at: ", first)
print("Second Hello at:", second)
📤 Output:
First Hello at: 0
Second Hello at: 8
How It Works
find("Hello", 7, 15) searches only in text[7:15], which is " Hello, ". The second "Hello" starts at index 8 in the full string.
Lowercase "world" does not match uppercase "World". Folding both sides with .lower() enables case-insensitive searching.
Example 5 — find() vs index()
See how the two methods differ when a substring is missing.
python
text = "Hello, World!"
sub = "Python"
print("find(): ", text.find(sub))
try:
print("index():", text.index(sub))
except ValueError as e:
print("index() raised ValueError:", e)
📤 Output:
find(): -1
index() raised ValueError: substring not found
How It Works
find() returns -1 quietly—good when missing text is normal.
index() raises ValueError—good when missing text means something went wrong.
For finding all occurrences, loop with find() and an increasing start index.
Applications
🚀 Common Use Cases
Parse emails — find "@" to split username and domain.
Log analysis — locate error keywords and extract surrounding text.
File paths — find the last "." before extracting an extension (often rfind() is better).
Validation — check that required markers appear in user input.
Text extraction — find a delimiter, then slice from that index onward.
🧠 How find() Works
1
Python defines the search range
The method uses start and end to slice the string, or searches the full string by default.
Range
2
Left-to-right scan
Python compares the substring at each position, case-sensitively, until a match is found or the range ends.
Search
3
Index or -1 is returned
On success, the starting index of the match is returned. On failure, -1 is returned.
Result
=
🔍
Location found
Use the index to slice, replace, or validate text at that position.
Important
📝 Notes
-1 means “not found”—do not use it as a slice index without checking first.
find() returns only the first match; use a loop or count() for multiple occurrences.
For the last occurrence, use rfind() instead.
An empty substring "" always matches at index 0 (or at start when given).
Wrap Up
Conclusion
The find() method is Python’s safe way to locate substrings by index. It returns -1 instead of raising an error when text is missing, which makes it ideal for everyday search and parsing tasks.
Pair it with slicing to extract portions of text, use start and end to narrow the search, and reach for index() only when a missing substring should fail loudly.
Pass start to find second and later occurrences in a loop
Use rfind() when you need the last match
❌ Don’t
Confuse -1 with “last character” in slicing
Use find() when you need a count—use count()
Assume case-insensitive matching without normalizing case
Use index() when missing text is an expected outcome
Forget that only the first match is returned
Summary
Key Takeaways
Knowledge Unlocked
Five things to remember about find()
Use these points when searching strings in Python.
5
Core concepts
🔍01
Returns Index
First match position.
Purpose
🔢02
-1 = Missing
Safe, no exception.
Return
📝03
Three Params
sub, start, end.
Syntax
🔎04
Parse Text
Find then slice.
Use case
⚠05
vs index()
-1 vs ValueError.
Compare
❓ Frequently Asked Questions
find() searches a string for a substring and returns the index of the first match. If the substring is not found, it returns -1 instead of raising an error.
string.find(sub, start, end). sub is the substring to search for. start and end optionally limit the search to a slice of the string.
It returns -1. This makes it safe to use in conditionals: if text.find("Python") != -1: ...
Yes. find() treats uppercase and lowercase as different. "Hello".find("hello") returns -1. Use .lower() on both strings for a case-insensitive search.
Both return the index of the first match. find() returns -1 when not found; index() raises ValueError. Use find() when absence is expected; use index() when absence is an error.
No. find() only reads the string and returns an integer index. The original string stays unchanged.