Find index of last occurrence of a character in a Python string
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 |
if __name__ == '__main__': s = "Hello, World" c = 'o' index = s.rfind(c) if index != -1: print(f"Char '{c}' is found at index {index}") # Char 'o' is found at index 8 else: print("Char not found") |
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.
|
1 2 3 4 5 6 7 8 9 10 11 |
if __name__ == '__main__': s = "Hello, World" c = 'o' try: index = s.rindex(c) print(f"Char '{c}' is found at index {index}") # Char 'o' is found at index 8 except: print("Char not found") |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
import more_itertools if __name__ == '__main__': s = "Hello, World" c = 'o' index = next(more_itertools.rlocate(s, lambda x: x == c)) if index != -1: print(f"Char '{c}' is found at index {index}") # Char 'o' is found at index 8 else: print("Char not found") |
That’s all about finding the index of the last occurrence of a character in a string in Python.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)