string = "HELLO"
print string[::-1] #as expected
print string[0:6:-1] #empty string why ?
I was amazed to see how easy it is to reverse a string in python but then I struck upon this and got lost. Can someone please explain why the second reverse does not works ?
The reason the second string is empty is because you are telling the compiler to begin at 0, end at 6 and step -1 characters each time.
Since the compiler will never get to a number bigger than six by repeatedly adding -1 to 0 (it goes 0, -1, -2, -3, ...) the compiler is programmed to return an empty string.
Try string[6::-1], this will work because repeatedly adding -1 to 6 will get to -1 (past the end of the string).
Note: this is answer is mainly a compilation of @dmcdougall, @Ben_Love and @Sundeep's comments with a bit more explanation
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With