Python string Method - rindex()

www‮i.‬giftidea.com

The rindex() method is a built-in string method in Python that works similarly to the rfind() method, but it raises a ValueError exception if the specified substring is not found in the string.

The syntax for using rindex() method is as follows:

string.rindex(substring, start, end)

Here, string is the original string, substring is the substring to search for in the string, start is the starting index of the search (optional), and end is the ending index of the search (optional). If start and end are not specified, the search will begin at the end of the string.

The method returns the index of the last occurrence of substring in the string.

Here's an example of using the rindex() method:

string = "Hello, World!"
last_index = string.rindex("l")
print(last_index)

Output:

10

In the example above, the rindex() method was used to find the index of the last occurrence of the letter "l" in the original string. The resulting index is stored in the variable last_index. Note that the search started from the end of the string and found the "l" in "World" at index 10. If the substring was not found, the method would have raised a ValueError exception.