What is the string.rfind method in Python?

The rfind method in Python returns the index of the last occurrence of a substring in a string. If the substring is not present in the string, then -1 will be returned.

Syntax


string.rfind(substring [, start[, end]] )

Arguments

  • substring: String to be searched.

  • start: The index from which the substring search should start. This is an optional value, and by default, the value is 0. The start index is included.

  • end: The index to which the substring search should happen. This is an optional value, and by default, the value is the length of the string. This index is excluded.

Return value

This is the last index at which the substring is found. If the substring is not present, -1 is returned.

Code

string = "The Small Smaller";
print("The index of Small is")
print(string.rfind("Small"));
print("\nThe index of Big is")
print(string.rfind("Big"));
print("\nThe index of 'Small' from index 7")
print(string.rfind("Small", 7));
print("\nThe searching for 'Small' from index 1 and 10")
print(string.rfind("Small", 1, 10));
Index mapping for the string

Explanation

In the code above, we created a The Small, Smaller string.


string.rfind("Small")

  • We used the rfind method to check the last index at which Small is present in the string. We will get 10 as a result.

string.rfind("Big")

  • The word Big is not present in the string so the rfind method will return -1.

string.rfind("Small", 7)

  • In this case, the rfind method will search the Small string from index 7 and return the last index at which the Small string is present. We will get 10 as a result.

string.rfind("Small", 1,10)

  • In this case, the rfind method will search the Small string from index 1 to index 10 and return the last index at which the Small string is present. We will get 4 as a result.

Free Resources