开发者

Python: reverse a string [duplicate]

开发者 https://www.devze.com 2023-03-17 01:57 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicate: Reverse a string in Python
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

精彩评论

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