Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does Python return -1 for string.rfind(last character of string, 0, len(string) – 1)?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading