How do you reverse the letters in a string? [duplicate]
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?
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
With slice notation:
string = "Hello!"
reversed_string = string[::-1]
加载中,请稍侯......
精彩评论