rindex() searches from the right and returns the index of the last place where the substring starts, counted from the left. It works exactly like rfind(), with one difference: when the substring is missing it raisesValueError instead of returning -1.
That makes it the strict choice. Use it when a missing substring would be a bug and you want the program to stop loudly, and use rfind() when a missing substring is a normal case. Optional start and end limit the search to a slice.
text.rindex() is a method of the built-in str type: call it on a string with dot notation. No import is needed, and it never changes the original string.
Syntax
Pass the substring to look for. start and end are optional.
Raises ValueError. The substring is not in the string.
Use rfind() to get -1 instead of an error, and index() for the first match.
Library declarations
python
str.rindex(sub[, start[, end]]) -> int
# returns: the highest index where sub starts
# raises: ValueError if sub is not found; TypeError if sub is not a string
Parameters
Parameter
Description
sub
Required. The substring to look for. It must be a string.
start
Optional. Index where the search area begins. Default 0.
end
Optional. Index where the search area stops, exclusive. Default is the end of the string.
Return Value
Return Value
Description
int
The index of the last match, counted from the left. If there is no match, ValueError is raised instead.
Python Examples
Example 1 — Find the Last Match or Fail
Find the last letter, then handle a substring that is missing.
python
word = "mississippi"
print(word.rindex("s"))
print(word.rindex("ss"))
try:
word.rindex("z")
except ValueError:
print("z is not in the word")
Output
6
5
z is not in the word
How It Works
The last s. In "mississippi", the final s is at index 6.
A longer substring. The last "ss" starts at index 5, which is one earlier than the last single s.
A missing substring raises."z" is not present, so ValueError is raised and the except block prints the message.
Example 2 — Split a Setting at the Last Equals Sign
Cut a line at its last = so that earlier equals signs stay in the key.
python
line = "name=Ada=Lovelace"
cut = line.rindex("=")
key = line[:cut]
value = line[cut + 1:]
print(cut)
print(key)
print(value)
Output
8
name=Ada
Lovelace
How It Works
The last equals sign.rindex("=") returns 8, skipping the earlier one at index 4.
Key is the left part.line[:cut] keeps everything before the cut, including the first =.
Value is the right part.line[cut + 1:] starts just after the equals sign.
Example 3 — Choose Between the Two
Wrap rindex() in a helper that returns None, and compare it with rfind().