Skip to content
Tutorials Center
My learning

Topics

Python Reference ยท String Methods

Python str.index() method

Reference for Python str.index(): find the lowest index of a substring and raise ValueError when it is missing, with start and end bounds and try/except use.

The str.index() method returns the lowest index at which a substring occurs in a string. It behaves exactly like find(), except for one thing: when the substring is not found it raises ValueError instead of returning -1.

Choose index() when a missing substring is a real error that should stop the program, or when you prefer to handle the failure with try and except rather than testing for -1.

Python
print("banana".index("nan"))    # 2

Try it

Python index() and its exception

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Python index() versus find()

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Syntax

Python
str.index(sub)
str.index(sub, start)
str.index(sub, start, end)
Name Description
sub The substring to look for. Must be a str.
start Optional. Index where the search begins (default 0).
end Optional. Index where the search stops, exclusive (default len(s)).

Return value: the lowest index of sub in s[start:end], counted from the start of s.

Raises: ValueError ("substring not found") if there is no match; TypeError if sub is not a string.

Usage notes

  • Same as find() otherwise. Index values are relative to the whole string, and an empty substring matches at start.
  • No -1 pitfalls. With find() a result of -1 can be mistaken for a position, for example when used as a slice end. An exception cannot be ignored by accident.
  • Check first or catch. To test presence, use sub in s. To avoid a race between checking and searching in one expression, wrap index() in try/except ValueError.
  • Highest index: the rindex() method searches from the right and also raises ValueError; rfind() is its -1 counterpart.
  • Lists and tuples have their own index() that also raises ValueError; it compares whole elements, not substrings.
  • Case-sensitive. Normalize the case with lower() when needed.
  • Prefer partition() when you are splitting at a separator: it never raises and returns the pieces directly.