For Python str.rfind(sub[, start[, end]]) method, I think these are the default values for the start and end parameters:
start = 0
end = the index of the last character of the string, which is equivalent to the length of the string minus 1.
However, Python returns different results for lines 3 and 4 below. For line 3, Python returns 23 which is what I expect. For line 4, Python returns 14 when I expect a return value of 23.
Could you please help explain why lines 3 and 4 do not return the same value of 23?
a = "Autumn's the mellow time"
print("Length of a:", len(a))
print(a.rfind("e"))
print(a.rfind("e", 0, len(a) - 1))
Output:
Length of a: 24
23
14
>Solution :
This is because the third argument __end is exclusive.
So basically, you dont need to subtract 1.
This is quite common in lists (range) in python and particularly in slice notation.
So this works:
a = "Autumn's the mellow time"
print("Length of a:", len(a))
print(a.rfind("e"))
print(a.rfind("e", 0, len(a)))
which will give what you are seeking:
Length of a: 24
23
23
So, it was (conveniently) easier than you anticipated.