search

str.index

Like find(), but raises ValueError if the substring is not found. Use when the substring is expected to exist and its absence is an error.

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

Parameters

Parameter Purpose
sub substring to locate
start optional slice start
end optional slice end

Examples

>>> 'hello world'.index('world')
6

returns index of first match

>>> 'hello'.index('z')
Traceback (most recent call last):
  ...
ValueError: substring not found

raises ValueError on miss (unlike find)

>>> 'ababab'.index('a', 2)
2

start argument narrows search window

>>> 'abc'.index('')
0

empty substring matches at 0

Gotcha

Use find() if you want a sentinel -1 instead of an exception. Prefer index() when a missing substring genuinely indicates a bug.

Related methods

← All Python string methods · Python built-ins