May 13, 2008

python reverse string

What is the best way to reverse a string?

In 2.4, a new builtin, reversed(), makes it so you can reverse a string like this:

>>> s = "some string"
>>> rev = "".join(reversed(s))
>>> print rev



It can be especially useful when you want to iterate over a string in reverse order:

>>> for x in reversed("some string"):
... print x