-2

Possible Duplicate:
Reverse a string in Python

Its been stumping me despite my initial thoughts that it would be simple.

Originally, I thought I would have have it print the elements of the string backwards by using slicing to have it go from the last letter to the first.

But nothing I've tried works. The code is only a couple lines so I don't think I will post it. Its extraordinarily frustrating to do.

I can only use the " for ", "while", "If" functions. And I can use tuples. And indexing and slicing. But thats it. Can somebody help?

(I tried to get every letter in the string to be turned into a tuple, but it gave me an error. I was doing this to print the tuple backwards which just gives me the same problem as the first)

I do not know what the last letter of the word could be, so I have no way of giving an endpoint for it to count back from. Nor can I seem to specify that the first letter be last and all others go before it.

Community
  • 1
  • 1
Micrified
  • 3,338
  • 4
  • 33
  • 59

2 Answers2

6

You can do:

>>> 'Hello'[::-1]
'olleH'

Sample

Mike Christensen
  • 88,082
  • 50
  • 208
  • 326
0

As Mike Christensen above wrote, you could easily do 'Hello'[::-1].

However, that's a Python-specific thing. What you could do in general if you're working in other languages, including languages that don't allow for negative list slicing, would be something more like:

def getbackwards(input_string):
   output = ''
   for x in range(0,len(input_string),-1):
       output += input_string[x]
   return output

You of course would not actually do this in Python, but just wanted to give you an example.

jdotjdot
  • 16,134
  • 13
  • 66
  • 118