Home / Python / Reference / String methods

Python string index() method

Like find, but raises ValueError if the text is missing.

Syntax

str.index(sub)

Use it when the text must be there, so a missing value is a clear error rather than a silent -1.

Parameters

subthe text to look for

Return value

int

Example

Code

print("hello".index("l"))
try:
    "hello".index("z")
except ValueError as e:
    print("ValueError:", e)

Output

2
ValueError: substring not found

Related

Learn it step by step in the free lesson Strings, with exercises that check your answers.