Confessions of a Python fanboy

Terry Reedy tjreedy at udel.edu
Thu Jul 30 16:55:17 EDT 2009


superpollo wrote:
> r wrote:

> how to reverse a string in python? must i usa a temp? like:
> 
>  >>> s = "ciccio"
>  >>> l = list(s)
>  >>> l.reverse()
>  >>> s = "".join(l)
>  >>> s
> 'oiccic'
>  >>>
> 
> ???

No.
 >>> ''.join(list(reversed('abc')))
'cba'
 >>> 'abc'[2::-1]
'cba'
 >>> 'abc'[1000000000::-1]
'cba'

Any int >= len(string)-1 will do, so the call to len will usually not be 
necessary.

Needing strings reversed is not common.  More common might be

for char in reversed(somestring): process(char)

Terry Jan Reedy




More information about the Python-list mailing list