Python Glossary Русский

all Python 3Strings (str)function

str.index

search

Like find, but raise ValueError when the substring is not found.

Syntax

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

Use index when a missing substring means the program is wrong: it fails loudly at the point of the mistake, whereas find's -1 quietly flows into a slice or into arithmetic and silently counts from the end of the string instead. When absence is a normal case, either check find's result explicitly or catch ValueError specifically, not a bare Exception.

Examples

print('hello'.index('e'))    # → 1
print('abcabc'.index('c'))   # → 2
print('hello'.index('l', 3))  # → 3

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy