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
| Parameter | Description |
|---|---|
sub |
The substring to look for. |
start, end optional |
Only search this slice. |
Return value
The index (an int).
Examples
print("hello".index("l"))
try:
"hello".index("z")
except ValueError as e:
print("ValueError:", e)
Output
2 ValueError: substring not found
line = "key=value"
sep = line.index("=")
print(line[:sep], "->", line[sep + 1:])
Output
key -> value
Version history
| Version | Change |
|---|---|
| Python 3.0 | Added |
Related
str.find()· Return the lowest index where a substring is found, or -1 if it isn't. Optional start and end limit the search.str.rindex()· Return the highest index of a substring, like rfind(), but raise ValueError when it is not found.str.count()· Return the number of non-overlapping occurrences of a substring, optionally only between start and end positions.- Python Strings · tutorial