Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reverse string Python slice notation

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 ?

like image 562
bawejakunal Avatar asked Feb 12 '26 03:02

bawejakunal


1 Answers

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

like image 79
boboquack Avatar answered Feb 14 '26 21:02

boboquack



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!