The rfind method
The rfind
method returns the index of the substring match from the end of the string. In the first parameter of the method, we specify the string or substring we want to find, in the second optional parameter - the index of the start of the search, in the third optional parameter - the index of the end of the search. If the substring is not found, the method will return the number -1
.
Syntax
string.rfind(what to find, [search start index], [search end index])
Example
Let's find the position of the first substring 'a'
from the end of the string:
txt = 'abacdea'
print(txt.rfind('a'))
Result of code execution:
6
Example
Now let's set the search boundaries:
txt = 'abacdea'
print(txt.rfind('a', 1, 3))
Result of code execution:
2
Example
Now let's try to find a non-existent substring using the rindex
method:
txt = 'abacdea'
print(txt.rfind('f'))
Result of code execution:
-1
See also
-
method
find
,
which returns the position of a substring in a string -
method
index
,
which returns the position of a substring in a string -
method
rindex
,
which searches for the position of a substring from the end of a string -
method
count
,
which returns the number of occurrences of a substring in a string -
method
endswith
,
which checks for a substring from the end of a string