Python string rindex() method
Example
The position of the last occurrence of the string "China" in the text is:
txt = "China is a great country. I love China." x = txt.rindex("casa") print(x)
Definition and Usage
The rindex() method finds the last occurrence of the specified value.
If the value is not found, the rindex() method will raise an exception.
The rindex() method is almost the same as the rfind() method. See the following examples.
Syntax
string.rindex(value, start, end)
Parameter Value
Parameter | Description |
---|---|
value | Required. The value to be searched for. |
start | Optional. Where to start the search. The default is 0. |
end | Optional. Where to end the search. The default is the end of the string. |
More Examples
Example
Where is the last occurrence of the letter "e" in the text?
txt = "Hello, welcome to my world." x = txt.rindex("e") print(x)
Example
If the search is only between positions 5 and 10, where is the last occurrence of the letter "e" in the text?
txt = "Hello, welcome to my world." x = txt.rindex("e", 5, 10) print(x)
Example
If the value is not found, the rfind() method returns -1, but the rindex() method will raise an exception:
txt = "Hello, welcome to my world." print(txt.rfind("q")) print(txt.rindex("q"))