Python string rfind() method
Python String rfind() Method
Description
The rfind() method returns the index of the last occurrence of a substring, or -1 if the substring does not exist. You can optionally limit the search to the string [beg:end].
Syntax
The syntax of the rfind() method is as follows:
var.rfind(sub, beg = 0, end = len(string))
Parameters
- sub – Specifies the string to search for.
- beg – The starting index, which defaults to 0.
- end – The ending index, which defaults to the length of the string.
Return Value
This method returns the last index if the result is found, otherwise returns -1.
Example
The following example demonstrates the use of the rfind() method.
var = "Explicit is better than implicit."
var1 = var.rfind('i')
print ("Original string:", var)
print ("Last index of 'i':", var1)
var2 = var.rfind('x', 10, -1)
print ("Last index of 'x':", var2)
When you run this program, it will produce the following output −
Original string: Explicit is better than implicit.
Last index of 'i': 30
Last index of 'x': -1
Since the letter “x” does not exist starting from the 10th index, “-1” is returned.