Skip to main content

rfind()

The rfind() method in Python is a string method that is used to find the last occurrence of a specified substring within a string. It returns the highest index of the substring within the string. If the substring is not found, it returns -1.

Parameter Values

Parameter Description
sub

The sub parameter specifies the string to search for in the given string.

start

The start parameter is optional and specifies the starting index of the search.

end

The end parameter is optional and specifies the ending index of the search.

Return Values

The rfind() method in Python returns an int indicating the last position of a substring.

How to Use rfind() in Python

Example 1:

The rfind() method returns the highest index of the specified substring within the given string. If the substring is not found, it returns -1.

text = 'Python is awesome, Python is great'
print(text.rfind('Python')) # Output: 20
Example 2:

If the rfind() method is used with additional parameters, it searches for the substring within the specified range of indices.

text = 'Python is awesome, Python is great'
print(text.rfind('Python', 0, 10)) # Output: -1
Example 3:

The rfind() method is case-sensitive, so make sure the substring matches exactly.

text = 'Python is awesome, Python is great'
print(text.rfind('python')) # Output: -1