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 ?

5
  • 2
    Did you read the documentation? Commented Oct 26, 2016 at 3:35
  • 1
    I imagine you want to reverse the indices, too. See the documentation for more details. python In [14]: s = 'HELLO' In [15]: s[6:0:-1] Out[15]: 'OLLE' Commented Oct 26, 2016 at 3: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 ? Commented Oct 26, 2016 at 3: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. Commented Oct 26, 2016 at 3:45
  • 1
    see also: stackoverflow.com/questions/509211/…... and I think you can get it working explicitly with string[4::-1] but not explicitly specifying the end value also.. Commented Oct 26, 2016 at 4:28

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.