Python String index() function returns the lowest index where the specified substring is found. If the substring is not found then ValueError
is raised.
Python String index() syntax
This function syntax is:
str.index(sub[, start[, end]])
The start parameter default value is 0 and it’s an optional argument.
The end argument default value is length of the string, it’s an optional argument.
We should use the index() function when we want to know the index position of the substring. For checking if a substring is present, we can use in operator.
Python string index() vs find()
Python string index() function raises ValueError if substring is not found whereas find() function returns -1. This is the only difference between these functions.
Python String index() examples
Let’s look at some simple examples of index() function.
s = 'abcd1234dcba'
print(s.index('a'))
print(s.index('cd'))
print(s.index('1', 0, 5))
Output:
0
2
4
Now let’s look at another example where the substring is not present and ValueError is thrown. I will use a try-except block to catch the exception and print its message.
s = 'abcd1234dcba'
try:
print(s.index('1', 0, 2))
except ValueError as ve:
print(ve)
Output: substring not found
Python String rindex()
Python string rindex() method is similar to index(), except that search is performed from right to left.
s = 'abcd1234dcba'
print(s.rindex('a'))
print(s.rindex('cd'))
print(s.rindex('1', 0, 5))
try:
print(s.rindex('1', 0, 2))
except ValueError as ve:
print(f'Error Message = {ve}')
Output:
11
2
4
Error Message = substring not found
Find all indexes for substring using index()
Python string index() method returns the first matched index. We can define a custom function to find all the indexes where the substring is found.
def find_all_indexes(input_str, search_str):
l1 = []
length = len(input_str)
position = 0
while position < length:
try:
i = input_str.index(search_str, position)
l1.append(i)
position = i + 1
except ValueError as ve1:
# finally exception will be raised because all the indexes are found
return l1
s = 'abaacdaa12aa2'
print(find_all_indexes(s, 'a'))
print(find_all_indexes(s, 'aa'))
Output:
[0, 2, 3, 6, 7, 10, 11]
[2, 6, 10]
Reference: Official Documentation
Good Job!