The rindex method
The rindex method returns the largest index of a substring match from the end of a string. In the first parameter of the method, we specify the string or substring we want to find, in the second optional parameter - the index of the start of the search, in the third optional parameter - the index of the end of the search.
Unlike the rfind method, the rindex method throws a ValueError exception if the substring is not found.
Syntax
string.rindex(what to find, [start searching], [end of search])
Example
Let's find the position of the first substring 'a' from the end of the string:
txt = 'abacdea'
print(txt.rindex('a'))
Result of code execution:
6
Example
Now let's set the search boundaries:
txt = 'abacdea'
print(txt.rindex('a', 1, 3))
Result of code execution:
2
Example
Now let's try to find a non-existent substring using the rindex method:
txt = 'abacdea'
print(txt.rindex('f'))
After executing the code, the method returned an error to us:
ValueError: substring not found
See also
-
method
replace,
which searches and replaces a substring in a string -
method
startswith,
which checks a substring from the beginning of a string -
method
rfind,
which returns the index of the last match of a substring in a string -
method
count,
which returns the number of occurrences of a substring in a string -
method
endswith,
which checks for a substring from the end of a string -
method
find,
which returns the index of the first match of a substring in a string