In Python, index() searches for a substring and returns the index of the first match. If the text is missing, it raises ValueError.
sub is required. Optional start and end limit the search to a slice. Use find() when absence should return -1 instead.
Syntax
Call index with the substring. Start with this line.
python
pos = text.index("Python")
Call
What it does
"hello".index("ll")
Returns 2.
"hello".index("x")
Raises ValueError when missing.
Catch ValueError when the substring might be absent, or switch to find().
Library declarations
python
str.index(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 ValueError if not found.
Python Examples
Example 1 — Required Substring Index
Get the first match when the substring is expected to exist.
python
text = "CodeToFun"
print(text.index("To"))
print(text.index("o")) # first "o" only
try:
print(text.index("Java"))
except ValueError as err:
print("error:", err)
Output
4
1
error: substring not found
How It Works
Match "To". Starts at index 4.
First only. Two "o" letters; index returns the first (1).
Missing text raises."Java" triggers ValueError.
Catch when needed. Use try/except for optional lookups.
Example 2 — Limit Search with start / end
Search inside a slice without building a new string first.
python
text = "one two two three"
print(text.index("two"))
print(text.index("two", 5))
try:
print(text.index("two", 0, 5))
except ValueError:
print("not in text[0:5]")
Output
4
8
not in text[0:5]
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.text[0:5] has no full "two" → error.
Slice semantics. Bounds behave like slicing.
Example 3 — index() vs find()
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. Required match → index; optional → find.
Fail fast. Raising early can reveal bad data sooner.
Frequently Asked Questions
It returns the first index of a substring, or raises ValueError if missing.
Python raises ValueError: substring not found.
Yes. Fold both sides with casefold() for case-insensitive search.