1

I am asked to have a string loop and print in reverse. I can get it to do this but why praytell is the last letter starting it off...

data = "Why am I doing this is reverse order."

for index in range(len(data)):
    print(index, data[-index])

0 W
1 .
2 r
3 e
4 d
5 r
6 o
7  
...

Ah this is the closest I have come....not adding data[:-index], [-index:]...they are all wrong...

data = "Why am I doing this is reverse order."

for index in range(len(data)):
    print(index, data[-index])


0 W
1 .
2 r
3 e
4 d
5 r
6 o
7  
...
Arghya Saha
  • 5,599
  • 4
  • 26
  • 48
  • 1
    `print(index, data[-index-1])` – Lante Dellarovere Apr 14 '19 at 15:05
  • Because lists have 0-based indexing forwards but you're out-by-one doing it in reverse (-1, not -0 is the last index). Consequently you end up looping around to the start of the list – roganjosh Apr 14 '19 at 15:07
  • There is a nice table in the [Strings](https://docs.python.org/3/tutorial/introduction.html#strings) section of the Tutorial that shows how positive and negative indexing work. It is the sixteenth example - or search the page for `One way to remember how slices work` – wwii Apr 14 '19 at 15:17
  • I see. Thanks very much. I totally get it now. =D – ManWithDirtyGlasses Apr 14 '19 at 23:00
  • My book is ok in explaining it, so thanks for the additional nfo/link. Everyone is so helpful here. – ManWithDirtyGlasses Apr 15 '19 at 02:04

3 Answers3

2

Dont use only - but substrac the index to the string len:

data = "Why am I doing this is reverse order."

l = len(data) - 1
for index in range(l+1):
    print(index, data[l-index])

Output:

0 .
1 r
2 e
...
34 y
35 h
36 W

Alternatively the pythonic way of doing this would be using reversed:

for l in reversed(data):
    print(l)

Also you can use slicing, data[::-1] but I would avoid this unless you want a reversed copy of the string.

Netwave
  • 40,134
  • 6
  • 50
  • 93
0

If you want it printed as a sentence, you can also:

reversed_data = data[::-1]
print(reversed_data)

OR

reversed_data = reversed(data)
print("".join(list(reversed_data)))

Or, if you want it character by character:

reversed_data = data[::-1]
for char in reversed_data:
    print(char)
reversed_data = reversed(data)
for char in reversed_data:
    print(char)
Zionsof
  • 1,196
  • 11
  • 23
0

The reason why your implementation doesn't work is because range(len(data)) starts at 0 up to n-1. However when your get data[-index] where index is 0 it return the 0 element of the string; the first letter.

An easy implementation is:

data = 'Hello world!'

# Print every letter on different line
for x in data[::-1]:
    print(x)

# Print the reverse string on one line
print(data[::-1])

refer to this post for how slicing works in python.

mathdugre
  • 98
  • 7