This post will discuss how to find the index of the last occurrence of a character in a string in Python.

1. Using rfind() function

A simple solution to find the last index of a character in a string is using the rfind() function, which returns the index of the last occurrence in the string where the character is found and returns -1 otherwise.

Download  Run Code

2. Using rindex() function

Alternatively, you can use the rindex() function, which differs from the rfind() function as rfind() returns -1 while rindex() raises an exception ValueError when the character is not found.

Download  Run Code

3. Using more_itertools.rlocate() function

Finally, you can use the more_itertools.rlocate() function to search for specific characters in a string. It yields an index of each character in the string for which the specified predicate is satisfied.

Download Code

That’s all about finding the index of the last occurrence of a character in a string in Python.