Tutorial Study Image

Python rfind()

The rfind() function in python helps to return the highest index means the last occurrence of the given substring from the original string. If the substring is not found the function will return -1. We can also specify the starting and ending positions for the search.

str.rfind(sub[, start[, end]] ) #where start & end are integer values

rfind() Parameters:

The rfind() function takes three parameters. This method is similar to the rindex() method the difference is that, if the substring is not found in the rindex() method it will raise a ValueError exception,

Parameter Description Required / Optional
sub The string to search for Required
start Where to start the search. Default is 0 Optional
end Where to end the search. Default is to the end of the string Optional

rfind() Return Value

The return value is always an integer. The rfind() method always performs a case-sensitive search.

Input Return Value
If substring Integer(highest index)
If no substring -1

Examples of rfind() method in Python

Example 1: How rfind() works in Python?

string = "Hii, How are you."
# substring exist
val = string.rfind("o")
print("Substring1 index:", val)

# substring not exist
value = string.rfind("s")
print("Substring2 index:", value)



Substring1 index: 14
Substring2 index: -1

Example 2: How rfind() works with start and end in Python?

string = "Python programming language"  
# calling function  
string2 = string.rfind("m",5) # Only starting index is passed  
print("Substring index:", string2)

string2 = string.rfind("o",1,7) # Start and End both indexes are passed  
print("Substring index:", string2)


Substring index: 14
Substring index: 4