Python 3 reference · String Methods

Python String index() Method

Return the lowest index of a substring, like find(), but raise ValueError when it is not found.

Python 3 Since 3.0

Syntax

str.index(sub, start=0, end=len(s))

Parameters

ParameterDescription
sub The substring to look for.
start, end optional Only search this slice.

Return value

The index (an int).

Examples

Found and not foundTry it yourself
print("hello".index("l"))
try:
    "hello".index("z")
except ValueError as e:
    print("ValueError:", e)

Output

2
ValueError: substring not found
Use it when the substring must existTry it yourself
line = "key=value"
sep = line.index("=")
print(line[:sep], "->", line[sep + 1:])

Output

key -> value

Version history

VersionChange
Python 3.0Added