faqts : Computers : Programming : Languages : Python

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

15 of 16 people (94%) answered Yes
Recently 10 of 10 people (100%) answered Yes

Entry

What is the best way to reverse a string?

Mar 5th, 2005 03:59
Björn Lindqvist,


This is one way that works in all Pythons.

>>> s = "some string"
>>> rev = s[::-1]
>>> print rev

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