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 is0. 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));
Explanation
In the code above, we created a The Small, Smaller string.
string.rfind("Small")
- We used the
rfindmethod to check the last index at whichSmallis present in the string. We will get10as a result.
string.rfind("Big")
- The word
Bigis not present in the string so therfindmethod will return-1.
string.rfind("Small", 7)
- In this case, the
rfindmethod will search theSmallstring from index7and return the last index at which theSmallstring is present. We will get10as a result.
string.rfind("Small", 1,10)
- In this case, the
rfindmethod will search theSmallstring from index1to index10and return the last index at which theSmallstring is present. We will get4as a result.