The index() method searches a string for a substring and returns the index of the first match. Unlike find(), it raises ValueError when nothing is found—so it is ideal when a missing substring means something went wrong. It is a core tool for locating text and slicing strings with confidence.
01
Find Index
Locate first occurrence.
02
Returns int
Position of the match.
03
ValueError
Raised when missing.
04
start / end
Limit search to a slice.
05
Case-Sensitive
A ≠ a in matching.
06
vs find()
ValueError vs -1.
Fundamentals
Definition and Usage
In Python, index() 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, index() raises ValueError with the message substring not found.
💡
Beginner Tip
Use index() when you expect the substring to exist—such as parsing a fixed-format message. Use find() or sub in text when the substring might be absent and you want to handle that without exceptions.
Foundation
📝 Syntax
The index() method accepts one required and two optional parameters:
python
string.index(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 the first match on success.
On failure — raises ValueError if sub is not found in the search range.
Read-only — the original string is never modified.
Reference
↩ Return Value
On success, index() returns a non-negative integer: the index where the first character of sub appears in the string (or within the start–end slice). On failure, it raises ValueError—it never returns -1 like find().
python
text = "Hello, World!"
# Success: returns 7
position = text.index("World")
# Failure: raises ValueError
# text.index("Python")
Cheat Sheet
⚡ Quick Reference
Expression
Result
"Hello, World!".index("World")
7
"Hello, World!".index("Python")
ValueError
"banana".index("na")
2 (first match)
"banana".index("na", 3)
4 (search from index 3)
"ABC".index("b")
ValueError (case-sensitive)
Basic
text.index("error")
Index or ValueError
Slice
text.index("at", 5, 20)
Search in range
Safe
try: text.index(sub)
Catch ValueError
Extract
idx = text.index("@")
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 index()
Locate where "World" begins inside "Hello, World!".
Text: Hello, World!
Index: 7
Char: W
Matched: World
How It Works
Indices 0–6 are "Hello, "; index 7 is where "World" starts.
index() returns the index of the first character of the match.
Use that index to slice or inspect the matched text immediately.
Example 2 — Handling ValueError
When the substring is absent, index() raises an exception. Always handle it in production code.
python
text = "Hello, World!"
try:
position = text.index("Python")
print("Found at index:", position)
except ValueError as e:
print("Could not find 'Python':", e)
📤 Output:
Could not find 'Python': substring not found
How It Works
Without try/except, an uncaught ValueError stops your program. If missing text is possible, prefer find() or check with sub in text first.
📈 Practical Patterns
Slice limits, case rules, and comparison with find().
Example 3 — Using start and end
Search only within part of the string by passing slice boundaries—similar to find().
python
text = "Hello, Hello, World!"
first = text.index("Hello")
second = text.index("Hello", 7, 15)
print("First Hello at: ", first)
print("Second Hello at:", second)
📤 Output:
First Hello at: 0
Second Hello at: 7
How It Works
index("Hello", 7, 15) searches only in text[7:15], which is "Hello, W". The second "Hello" starts at index 7 in the full string.
Example 4 — Case Sensitivity
index() does not ignore letter case.
python
text = "Hello, World!"
try:
text.index("world")
except ValueError:
print("Lowercase 'world' not found (case-sensitive).")
position = text.index("World")
print("Exact match 'World' at index:", position)
📤 Output:
Lowercase 'world' not found (case-sensitive).
Exact match 'World' at index: 7
How It Works
Lowercase "world" does not match uppercase "World". For case-insensitive searches, normalize with .lower() on both sides before calling index().
Example 5 — index() vs find()
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 signals invalid input or a bug.
Both return the same index when the substring is found.
Applications
🚀 Common Use Cases
Strict parsing — require a delimiter like "@" in email addresses and fail fast if it is missing.
Config validation — ensure required keys or markers appear in a template string.
Protocol messages — locate fixed headers in known-format log lines.
Text extraction — find a delimiter, then slice from that index onward.
Asserting invariants — use index() in tests or internal code where absence should never happen.
🧠 How index() 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 exception
On success, the starting index is returned. On failure, ValueError is raised.
Result
=
🔢
Position confirmed
Use the index to slice, replace, or validate text at that position.
Important
📝 Notes
index() returns only the first match; use a loop with an increasing start to find later occurrences.
For the last occurrence, use rindex() instead.
Like find(), index() is case-sensitive—normalize case when needed.
An empty substring "" always matches at index 0 (or at start when given).
Store the result in a variable if you need the index more than once to avoid redundant searches.
Wrap Up
Conclusion
The index() method is Python’s strict way to locate substrings by index. It returns the position of the first match and raises ValueError when text is missing, which makes it ideal for parsing tasks where absence means invalid data.
Wrap calls in try/except when input is unpredictable, use start and end to narrow the search, and reach for find() when a missing substring is an ordinary outcome.
Use index() when a missing substring indicates bad input
Wrap calls in try/except ValueError when input is uncertain
Use .lower() for case-insensitive searches
Pass start to find second and later occurrences in a loop
Store the index once if you reuse it for slicing
❌ Don’t
Call index() without handling ValueError on user input
Use index() when find() or in is clearer
Assume case-insensitive matching without normalizing case
Confuse index() with list .index()—same name, different types
Forget that only the first match is returned
Summary
Key Takeaways
Knowledge Unlocked
Five things to remember about index()
Use these points when searching strings in Python.
5
Core concepts
🔢01
Returns Index
First match position.
Purpose
⚠02
ValueError
Raised if missing.
Return
📝03
Three Params
sub, start, end.
Syntax
🔎04
Strict Parse
Fail when required.
Use case
🔍05
vs find()
ValueError vs -1.
Compare
❓ Frequently Asked Questions
index() searches a string for a substring and returns the index of the first match. If the substring is not found, it raises ValueError instead of returning -1.
string.index(sub, start, end). sub is the substring to search for. start and end optionally limit the search to a slice of the string.
Python raises ValueError with the message "substring not found". Wrap the call in try/except when the substring might be absent.
Yes. "Hello".index("hello") raises ValueError. Convert both strings with .lower() for a case-insensitive search.
Both return the index of the first match. index() raises ValueError when not found; find() returns -1. Use index() when a missing substring is an error; use find() when absence is normal.
No. index() only reads the string and returns an integer index. The original string stays unchanged.