Reverse a string in Python
Using slicing:
>>> 'hello world'[::-1]
'dlrow olleh'
Slice notation takes the form [start:stop:step]
. In this case, we omit the start
and stop
positions since we want the whole string. We also use step = -1
, which means, "repeatedly step from right to left by 1 character".
@Paolo's s[::-1]
is fastest; a slower approach (maybe more readable, but that's debatable) is ''.join(reversed(s))
.