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
  • 38,002
  • 70
  • 184
  • 260

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
  • 507,862
  • 82
  • 626
  • 550
2

With slice notation:

string = "Hello!"
reversed_string = string[::-1]
Michael Foukarakis
  • 39,737
  • 6
  • 87
  • 123