0

I know there are better ways to print things backwards. But for some reason I can't get this to work. Any ideas why?

fruit = 'banana'
index = 0
while index < len(fruit):
    print fruit[-(index)]
    index = index + 1
3
  • 1
    see stackoverflow.com/questions/931092/reverse-a-string-in-python Commented Sep 27, 2014 at 20:29
  • @gabber, the OP has stated they already know there are other ways to reverse a string, they want to know why their code is not working Commented Sep 27, 2014 at 20:35
  • BTW, the () around index are redundant, and add clutter to the code. Commented Sep 27, 2014 at 20:44

1 Answer 1

7

You reversed everything but the b, because you started at 0, and -0 is still 0.

You end up with the indices 0, -1, -2, -3, -4, -5, and thus print b, then only anana in reverse. But anana is a palindrome, so you cannot tell what happened! Had you picked another word it would have been clearer:

>>> fruit = 'apple'
>>> index = 0
>>> while index < len(fruit):
...     print fruit[-index]
...     index = index + 1
... 
a
e
l
p
p

Note the a at the start, then pple correctly reversed.

Move the index = index + 1 up a line:

index = 0
while index < len(fruit):
    index = index + 1
    print fruit[-index]

Now you use the indices -1, -2, -3, -4, -5 and -6 instead:

>>> fruit = 'banana'
>>> index = 0
>>> while index < len(fruit):
...     index = index + 1
...     print fruit[-index]
... 
a
n
a
n
a
b
>>> fruit = 'apple'
>>> index = 0
>>> while index < len(fruit):
...     index = index + 1
...     print fruit[-index]
... 
e
l
p
p
a

I removed the (..) in the expression -(index) as it is redundant.

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

1 Comment

One of those weird situations where the only reason it's hard to debug is the particular example used. Not many words are a letter followed by an palindrome.

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.