Python String rfind() Method

The rfind() method is used to find the last occurrence of a substring in a string. It returns the highest index where the substring is found, or -1 if it is not found.

Syntax

string.rfind(substring, start, end)

Parameters

substring: The substring to search for.

start (Optional): The starting index to begin the search. Default is 0.

end (Optional): The ending index to stop the search. Default is the end of the string.

Return Value

Returns the highest index where the substring is found, or -1 if not found.

Examples

Basic Usage

text = "hello hello hello"
index = text.rfind("hello")
print(index) # Output: 12

If Substring is Not Found

The rfind() method returns -1 if the substring is not found within the string.

text = "hello hello hello"
index = text.rfind("apple")
print(index) # Output: -1

With start Parameter

Providing only the start parameter is useful when you want to search for a substring starting from a specific index and going toward the end of the string.

text = "python is aweseome python is easy"
index = text.rfind("python", 20 )
print(index) # Output: -1

In this example, the rfind() starts searching for a substring "python" from index 20 to the end of the string. Since there is no substring "python" after index 20, it returns -1, indicating that the substring was not found.

With start and end Parameters

Providing both start and end parameters is useful when you want to search for a substring within a specific range of the string.

text = "hello hello hello"
index = text.rfind("hello", 0, 11)
print(index) # Output: 6

In this example, the substring "hello" appears three times at indices, 0, 6, and 12. By passing 0 as the start and 11 as the end parameters to the rfind() method, it searches for the last occurrence of "hello" within the range from index 0 up to (but not including) index 11. Within this range, "hello" appears at indices 0 and 6, and the last occurrence is at the index 6. Therefore, rfind() returns 6.

Finding a Single Character

The rfind() method can also be used to locate the last occurrence of a single character in a string.

text = "banana"
index = text.rfind("a")
print(index) # Output: 5

Case-sensitive

The rfind() method is case-sensitive, meaning it treats uppercase and lowercase letters as distinct characters.

text = "Python is awesome. Python is easy"
index = text.rfind("python")
print(index) # Output: -1

In this example, the rfind() method returns -1 because it is case-sensitive. It looks for the exact lowercase substring "python" but the text contains "Python" with an uppercase "P". Since the cases don’t match, no match is found.

find() vs rfind()

The find() method searches for a substring starting from the beginning (left) of the string and returns the index of its first occurrence.

The rfind() method searches for a substring starting from the end (right) of the string and returns the index of its last occurrence.