Python string rfind() 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.rfind("casa") print(x)
Definition and Usage
The rfind() method finds the last occurrence of the specified value.
If the value is not found, the rfind() method will return -1.
The rfind() method is almost the same as the rindex() method. See the following examples.
Syntax
string.rfind(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.rfind("e") print(x)
Example
Where is the last occurrence of the letter "e" in the text if only the positions 5 and 10 are searched?
txt = "Hello, welcome to my world." x = txt.rfind("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"))