开发者

Python: reverse a string [duplicate]

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

Possible Duplicate:

Reverse a string in Python

I understand that data in Python (strings) are stored like lists

Example:

string1 = "foo"
"foo"[1] = "o"

How would I use the list.reverse function to reverse the开发者_Go百科 characters in a string? Such that I input "foo" and get returned back "oof"


You normally wouldn't.

>>> "foo"[::-1]
'oof'


Like this:

''.join(reversed(myString))


If you want to use list.reverse, then you have to do this:

c = list(string1)
c.reverse()
print ''.join(c)

But you are better using ''.join(reversed('foo')) or just 'foo'[::-1]

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜