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.
string.rfind(substring [, start[, end]] )
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.
This is the last index at which the substring is found. If the substring is not present, -1
is returned.
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));
In the code above, we created a The Small, Smaller
string.
string.rfind("Small")
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")
Big
is not present in the string so the rfind
method will return -1
.string.rfind("Small", 7)
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)
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.