main_string.rindex(search_string, start, end)
search_string
start
end
my_str='Welcome to plus2net.com Python section'
output=my_str.rindex('co')
print(output) # output is 20
Using optional parameters start and end.
my_str='Welcome to plus2net.com Python section'
output=my_str.rindex('co',10,22)
print(output) # output is 20
If search string is not found then value error is generated.
my_str='Welcome to plus2net.com Python section'
output=my_str.rindex('co',10,21)
print(output)
Output
ValueError Traceback (most recent call last)
in ()
1 my_str='Welcome to plus2net.com Python section'
----> 2 output=my_str.rindex('co',10,21)
3 print(output)
ValueError: substring not found
rindex() method raise an exception if searched string is not found but rfind() returns -1 if searched string is not found. That is the main difference between rindex() and rfind()
The `rindex()` method can be used to find the last occurrence of a word within a string, which is useful for parsing or analyzing text.
my_str = "Find the last apple in the apple orchard"
position = my_str.rindex("apple")
print("Last 'apple' found at index:", position)
Last 'apple' found at index: 27
If we want to extract text after the last occurrence of a delimiter (e.g., a period or slash), `rindex()` can be extremely helpful.
file_path = "user/documents/reports/summary.pdf"
last_slash = file_path.rindex("/")
file_name = file_path[last_slash + 1:]
print("File name:", file_name)
File name: summary.pdf
We can specify search limits using the start and end parameters to find occurrences within a defined range.
my_str = "error1: info; error2: critical; error3: debug"
position = my_str.rindex("error", 0, 20)
print("Last 'error' found in range:", position)
Last 'error' found in range: 14
The `rindex()` method raises a `ValueError` if the substring is not found. We can handle this using a try-except block.
try:
position = "Hello World".rindex("Python")
print("Position:", position)
except ValueError:
print("Substring not found")
Output
Substring not found