English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
The rindex() method searches for the specified value in the string and returns the last position where it is found. If the substring is not found, an exception will be raised.
The syntax of rindex():
str.rindex(sub[, start[, end]])
The rindex() method takes three parameters:
sub -The substring to be searched in the str string.
startandend(Optional)-Search for the substring within str[start:end]
If the substring exists in the string, it will return the last position found in the string where the substring is located.
If the substring does not exist in the string, it will raiseValueErrorexception.
rindex() method is similar tostring rfind() method.
The only difference is that rfind() returns-1,while rindex() will raise an exception.
quote = 'Let it be, let it be, let it be' result = quote.rindex('let it') print("Substring 'let it':", result) result = quote.rindex('small') print("Substring 'small':", result)
When running the program, the output is:
Substring 'let it': 22 Traceback (most recent call last): File "...", line 6, in <module> result = quote.rindex('small') ValueError: substring not found
Note: In Python, indexing starts from 0, not1.
quote = 'Do small things with great love' # Search for substring ' small things with great love' print(quote.rindex('t', 2)) # Search for substring 'll things with' print(quote.rindex('th', 6, 20)) # Search for substring 'hings with great lov' print(quote.rindex('o small ', 10, -1))
When running the program, the output is:
25 18 Traceback (most recent call last): File "...", line 10, in <module> print(quote.rindex('o small ', 10, -1)) ValueError: substring not found