String method

str.index()

Returns the position where a piece of text first appears in a string, and raises ValueError when it is not found.

BeginnerEvery example below runs in your browser. Change the code and press Run.

str.index(sub[, start[, end]])

index() searches a string just like str.find(): it gives the position where sub first starts, counting from 0.

The difference is what happens on a miss. find() quietly returns -1; index() raises a ValueError. That is useful when the text must be there: the program stops with a clear error instead of carrying on with a wrong position.

Lists have an index() method too, which finds an item. On a string, sub can be longer than one character.

Parameters

ParameterWhat it is
sub
required
The text to look for.
start
optional, default 0
Where to begin searching.
end
optional, default len(str)
Where to stop searching.

Return value

The position (an int) of the first match. Raises ValueError if there is none.

Examples

1Find a position

Pythoneditable
word = "hello"
print(word.index("l"))
print(word.index("lo"))
Output
2
3

2Split a setting at the equals sign

Pythoneditable
line = "timeout=30"
eq = line.index("=")
key = line[:eq]
value = line[eq + 1:]
print(key, "->", value)
Output
timeout -> 30

3Handle a missing match

Pythoneditable
words = ["key=value", "broken line"]
for w in words:
    try:
        pos = w.index("=")
        print(w, "has = at", pos)
    except ValueError:
        print(w, "has no =")
Output
key=value has = at 3
broken line has no =

Catch ValueError when the text may be missing, or use find() and check for -1.

4Search inside a part of the string

Pythoneditable
date = "2026-03-14"
first = date.index("-")
second = date.index("-", first + 1)
print(first, second)
print(date[first + 1:second])
Output
4 7
03

Common mistakes

Not expecting the error

If the text might be missing, index() stops the program. Use in to check first, catch ValueError, or switch to find().

Pythoneditable
text = "hello"
try:
    print(text.index("z"))
except ValueError:
    print("ValueError: 'z' is not in the text")
print(text.find("z"))
Output
ValueError: 'z' is not in the text
-1

Questions people ask

When should I use index() instead of find()?

Use index() when a missing match is a real error you want to notice. Use find() when missing is normal and you will check for -1.

How do I find the last match?

Use rindex(): it works like index() but searches from the right.

Is str.index() the same as list.index()?

Same idea, different types: list.index() finds an item in a list, while str.index() finds text inside a string.

Spotted a mistake on this page? Tell us