tags:

views:

1052

answers:

2

There is no built in "reverse" function in Python's str object. What is the best way of implementing this?

If supplying a very concise answer, please elaborate on it's efficiency. Is the str converted to a different object, etc.

+38  A: 

How about:

>>> 'hello world'[::-1]
'dlrow olleh'

This is extended slice syntax. It works by doing [begin:end:step] - by leaving begin and end off and specifying a step of -1, it reverses a string.

Paolo Bergantino
+9  A: 

@Paolo's s[::-1] is fastest; a slower approach (maybe more readable, but that's debatable) approach is ''.join(reversed(s)).

Alex Martelli
A *lot* faster:$ python -m timeit s='s = "abcdef"' 'mystr = mystr[::-1]'1000000 loops, best of 3: 0.263 usec per loop$ python -m timeit s='s = "abcdef"' 'mystr = "".join(reversed(mystr))'100000 loops, best of 3: 2.29 usec per loop
telliott99