The index() method returns the index of a substring inside the string (if found). If the substring is not found, it raises an exception.
Example
index() Syntax
It's syntax is:
str.index(sub[, start[, end]] )
index() Parameters
The index() method takes three parameters:
- sub - substring to be searched in the string str.
- start and end(optional) - substring is searched within str[start:end]
index() Return Value
- If substring exists inside the string, it returns the lowest index in the string where substring is found.
- If substring doesn't exist inside the string, it raises a ValueError exception.
The index() method is similar to the find() method for strings.
The only difference is that find() method returns -1 if the substring is not found, whereas index() throws an exception.
Example 1: index() With Substring argument Only
Output
Substring 'is fun': 19
Traceback (most recent call last):
File "<string>", line 6, in
result = sentence.index('Java')
ValueError: substring not found
Note: Index in Python starts from 0 and not 1. So the occurrence is 19 and not 20.
Example 2: index() With start and end Arguments
Output
15
17
Traceback (most recent call last):
File "<string>", line 10, in
print(quote.index('fun', 7, 18))
ValueError: substring not found