3
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 ?

bawejakunal
  • 1,678
  • 2
  • 25
  • 54
  • 2
    Did you read the documentation? – BrenBarn Oct 26 '16 at 03:35
  • 1
    I imagine you want to reverse the indices, too. See [the documentation](https://docs.python.org/2/tutorial/introduction.html#strings) for more details. ```python In [14]: s = 'HELLO' In [15]: s[6:0:-1] Out[15]: 'OLLE' ``` – dmcdougall Oct 26 '16 at 03:40
  • yes I did, couldn't understand that, hence asked here if someone could please explain in simpler terms. I only got the `string[begin:end:step]` thing clear and according to that this should have worked no ? – bawejakunal Oct 26 '16 at 03:43
  • Like @dmcdougall said, perhaps you need to reverse the indices. You're telling the interpreter to start at index 0 and go to (past) the end, but backwards. You have nothing before the first index. – Ben Love Oct 26 '16 at 03:45
  • 1
    see also: https://stackoverflow.com/questions/509211/explain-pythons-slice-notation... and I think you can get it working explicitly with `string[4::-1]` but not explicitly specifying the end value also.. – Sundeep Oct 26 '16 at 04:28

2 Answers2

1

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

boboquack
  • 249
  • 5
  • 15
1

Slice notation is written as follows:

list_name[start_index: end_index: step_value]

The list indexes in python are not like the numbers present on number line. List indexes does not go to -1st after 0th index when step_value is -1.

Hence below results are produced

>>>> print string[0:6:-1]

>>>>

And

>>>> print string[0::-1]

>>>> H

So when the start_index is 0, it cant go in a cyclic order to traverse the indexes to -1, -2, -3, -4, -5, -6 for step_value is -1.

Similarly

>>>> print string[-1:-6:-1]

>>>> OLLEH

and

>>>> print string[-1::-1]

>>>> OLLEH

also

thus when the start_index is -1 it goes in a cyclic order to traverse the indexes to -1, -2, -3, -4, -5, -6 to give output OLLEH.

Its pretty straight forward to understand when start_index is 6 and step_value is -1

>>>> print string[6::-1]

>>>> OLLEH

Vishvajit Pathak
  • 3,351
  • 1
  • 21
  • 16