What is rfind() in Python?

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.

Syntax


string.rfind(sub, start, end)

Parameters

The rfind() function takes the following three parameters:

  1. substring (required): The substring to be found.

  2. start (optional): The starting index where the substring search should begin.

  3. end (optional): The ending index at which the search of the substring should stop.

Return value

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.

Code

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 index
find = string.rfind('to')
print(find)
# when the substring is not present
find = string.rfind('s')
print(find)
# substring search starting from index 10
find = string.rfind('i', 10)
print(find)
# substring search starting from index 10 and ending at index 30
find = string.rfind('o', 10, 30)
print(find)

Free Resources