String rindex() Method in Python

Python String rindex() Method

In Python, the rindex() method is a built-in string method that is used to find the last occurrence of a substring within a string. It is similar to the index() method, but instead of returning the index of the first occurrence of the substring, it returns the index of the last occurrence.

The syntax of the rindex() method is as follows:

string.rindex(substring, start, end)

Here, string is the original string, substring is the substring you want to find the last occurrence of, and start and end are optional parameters that specify the range of the string where the method should search for the substring. The search will be performed in the slice of the string from index start (inclusive) to index end (exclusive).

If the substring is found, rindex() returns the index of its last occurrence. If the substring is not found, it raises a ValueError.

Let's see some examples to better understand its usage:

# Example 1
sentence = "She sells seashells by the seashore."
index = sentence.rindex("se")
print(index)  # Output: 33

# Example 2
sentence = "She sells seashells by the seashore."
index = sentence.rindex("se", 0, 20)  # Searching only in the first 20 characters
print(index)  # Output: 12

# Example 3
sentence = "She sells seashells by the seashore."
try:
    index = sentence.rindex("sea")
    print(index)
except ValueError:
    print("Substring not found.")

In the first example, the rindex() method finds the last occurrence of the substring "se" in the sentence, which starts at index 33.

In the second example, we use the optional start and end parameters to limit the search to the first 20 characters. The method still finds the last occurrence of "se," which is at index 12 within that range.

In the third example, the substring "sea" is not found in the sentence, so it raises a ValueError, which we catch and handle by printing a message.