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.
print("banana".index("nan")) # 2
Try it
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.
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
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 atstart. - No
-1pitfalls. Withfind()a result of-1can 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, wrapindex()intry/except ValueError. - Highest index: the
rindex()method searches from the right and also raisesValueError;rfind()is its-1counterpart. - Lists and tuples have their own
index()that also raisesValueError; 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.
Related
str.find(),str.rfind(),str.count(),str.partition(),list- Lessons: Strings, String methods