开发者

How do you reverse the letters in a string? [duplicate]

This question already has answers here: Closed 11 years ago.

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]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜