Python string rindex() method with example

The rindex() method in Python is used to find the highest (rightmost) index of a specified substring or character within a string. It searches the string from right to left for the last occurrence of the specified substring or character and returns the index at which it is found. If the substring is not found, it raises a ValueError.

Here’s the syntax for the rindex() method:

str.rindex(substring, start, end)

substring is the substring you want to search for within the given string.

start (optional) is the index at which the search should begin. If not specified, the search starts from the end of the string.

end (optional) is the index at which the search should end. If not specified, the search goes up to the beginning of the string.

Here’s an example:

text = "apple,banana,banana,cherry"
index = text.rindex("banana")
print("Index of 'banana':", index)

Output:

Index of 'banana': 13

If the substring is not found, it will raise a ValueError. You can catch this exception to handle the case when the substring is not in the string:

try:
  index = text.rindex("grape")
  print("Index of 'grape':", index)
except ValueError:
  print("'grape' not found in the string.")

Output:

'grape' not found in the string.

The rindex() method is useful when you need to find the last occurrence of a substring in a string, which can be handy for various text processing and parsing tasks.

Example 1

This code reverses a string by finding the last occurrence of a character (in this case, “H”) and slicing from that position to the beginning of the string.

Reversing a String Using rindex() and Slicing:
text = "Hello, World!"
reversed_text = text[text.rindex("H")::-1]
print(reversed_text)

Example 2

extracts the file extension from a file path by finding the last occurrence of the dot (.) character.

file_path = "/path/to/myfile.txt"
extension_index = file_path.rindex(".")
file_extension = file_path[extension_index + 1:]
print(f"File extension: {file_extension}")

Example 3

Search for the Last Occurrence of a Substring.

log_data = "Error: File not found. Error: Connection lost."
last_error_index = log_data.rindex("Error")
print(f"Last 'Error' at index {last_error_index}.")

Output:

Last 'Error' at index 23.

Leave a Reply

Your email address will not be published. Required fields are marked *