str.index
Find the first occurrence of the substring sub in the string.
Python 3.13
str.index(sub[, start[, end]])Parameters
- substr
- The substring to find.
- startintoptional
- The index where the search starts.
- endintoptional
- The index before which the search stops.
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.
