Python String rfind() Method

Searches the string for a given substring, starting from the right


The rfind() method searches for the last occurrence of the specified substring sub and returns its index.

If specified substring is not found, it returns -1.

The optional arguments start and end are used to limit the search to a particular portion of the string.



Python string rfind() method parameters
subRequiredAny string you want to search for
startOptionalAn index specifying where to start the search.
Default is 0.
endOptionalAn index specifying where to stop the search.
Default is the end of the string.

Basic Examples

Example: Find last occurrence of the substring ‘Big’

S = 'Big, Bigger, Biggest'
x = S.rfind('Big')
print(x)    # 13

rfind() method returns -1 if the specified substring doesn’t exist in the string.


S = 'Big, Bigger, Biggest'
x = S.rfind('Small')
print(x)	# -1

If you want to search the string from the middle, specify the start and end parameters.

Example: Search the string from position 2 to 10

S = 'Big, Bigger, Biggest'
x = S.rfind('Big',2,10)
print(x)    # 5

rfind() vs rindex()

The rfind() method is identical to the rindex() method.

The only difference is that the rindex() method raises a ValueError exception, if the substring is not found.


S = 'Big, Bigger, Biggest'
x = S.rfind('Small')
print(x)    # -1
# ValueError: substring not found
S = 'Big, Bigger, Biggest'
x = S.rindex('Small')