0

Possible Duplicate:
reverse a string in Python

I'm trying to understand how to reverse the letters in a string. Let's say that I have hello and am looking for the output olleh how would I implement this using the list as a tool?

Community
  • 1
  • 1
locoboy
  • 36,684
  • 67
  • 180
  • 255

2 Answers2

4

Using slice notation,

forwards = "hello"
backwards = forwards[::-1]

(The third section of slice notation is the step; in this case, -1 makes it step backwards through the entirety of the string, effectively reversing it.)

or, using the reversed() function:

backwards = ''.join(reversed(forwards))

(Note that without the ''.join(), you'd get a <reversed object at 0x1215a10> instead.)


>>> print backwards
olleh
Amber
  • 477,764
  • 81
  • 611
  • 541
2

With slice notation:

string = "Hello!"
reversed_string = string[::-1]
Michael Foukarakis
  • 38,030
  • 5
  • 79
  • 118