The rfind()
method in Python returns the highest index of the specified substring if that substring is found in a string.
If the substring is not found, the method returns -1.
string.rfind(sub, start, end)
The rfind()
function takes the following three parameters:
substring
(required): The substring to be found.
start
(optional): The starting index where the substring search should begin.
end
(optional): The ending index at which the search of the substring should stop.
The return value is an integer that tells the highest index of the specified substring.
As mentioned above, if the substring is not found, it returns -1.
In the code below, the rfind()
function returns the substring index, and if absent, it gives -1.
In the third example, we specified the starting index. In the fourth example, wespecified both ending and starting indices.
The function returns the highest index of the substring between the specified indices.
string = 'Welcome to Educative, to the world of learning'# with no start and end indexfind = string.rfind('to')print(find)# when the substring is not presentfind = string.rfind('s')print(find)# substring search starting from index 10find = string.rfind('i', 10)print(find)# substring search starting from index 10 and ending at index 30find = string.rfind('o', 10, 30)print(find)