str.index
Find the first occurrence of the substring sub in the string.
Python 3.13
str.index(sub[, start[, end]])- [ ]optional part
- sub
- The substring to find.str
- start
- The index to start searching from, 0 by default; a negative one counts from the end.intOptional
- end
- The index before which the search stops, the end by default; a negative one counts from the end.intOptional
Return value
The index of the first occurrence; raises ValueError if the substring is missing.
Examples
Position of a found substring
Python 3.13
print('hello'.index('l'))2
Error for a missing substring
Python 3.13
try:
'hello'.index('z')
except ValueError as error:
print(error)substring not found
Details
If the substring may be missing, str.find is more convenient: it returns -1 instead of raising an exception.
