Python String – rfind() method

This method in python finds the first occurrence from the right side of the string (from the end) and returns the index of the first character of the value. If not found it returns -1.

Syntax:

string.rfind(value, starting_index, ending_index)

Note:

indexing starts from the left (it doesn’t change).

Example 1:

s = “CodeWindow offers IT related news and offers solved programs too
x = s.rfind(“offers“, 0, 40)
print(x)

Output:

38

Explanation:

The word “offers” first occurs at index 38 from the right side of the string i.e. from the end.

Example 2:

s = “CodeWindow offers IT related news
x = s.rfind(‘q‘, 0, 33)
print(x)

Output:

-1

Explanation:

Here the character “q” is not present in the whole string. Hence it returned -1.

Note:

The difference between rindex and rfind is that rfind returns -1 if the value is not there in the string on the other hand rindex throws an error if not found.

You Missed