Reversing a string

There are a few ways of reversing a string in Python. All of these examples assume that you want to store the reversed string in another variable.

The brute force method

Long winded and very inefficient, but very much from first principles.

i = 'Hello World!'
j = ''
for j in range(len(i)-1,-1,-1):
  j += i[j]

Extended slice syntax

Normal Python string/list slicing is of the form string[start:stop:step] (this looks and behaves a lot like the range() function) where ...
  • start is the index of the first position in the slice;
  • stop is the index+1 of the last position in the slice (be careful here!);
  • step is the number of indices to increment each time;
If you omit any of these values from the slice, they default to 0, the last index in the string/list and +1, so ...

>>> i = 'Hello World!'
>>> i[::]
Hello World!

But, if you change the step value to -1 (increment by -1 or, decrement) , something magical happens ...

>>> i = 'Hello World!'
>>> j = i[::-1]
>>> j
!dlroW olleH

Use the reverse() method of a list

It's fairly safe to use reverse() to reverse a string because you have to convert the string to a list first (a string has no reverse() method), but be careful using this on a list as the reverse() method performs an in-place reversal and the original order will be lost.

>>> i = "Hello World!"
>>> j = list(i)
>>> j
['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd', '!']
>>> j.reverse()
>>> j
['!', 'd', 'l', 'r', 'o', 'W', ' ', 'o', 'l', 'l', 'e', 'H']
>>> j = ''.join(j)
>>> j
'!dlroW olleH'

Be careful - because j.reverse() doesn't actually return a value (it's not a function), you can't do this ...

>>> j = ''.join(list(i).reverse())
Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
TypeError: can only join an iterable

Use the reversed() method

Look carefully! This is reversed() rather than reverse(). This is a function which returns a reversed version of the string (not the string actually, so there is a little more work to do before we can print it) so it's quite safe.

>>> i = 'Hello World!'
>>> j = reversed(i)
>>> j
<reversed object at 0x0000024C7ADDB310>
>>> list(reversed(i))
['!', 'd', 'l', 'r', 'o', 'W', ' ', 'o', 'l', 'l', 'e', 'H']
>>> j = ''.join(list(reversed(i)))
>>> j
'!dlroW olleH'

Notice that this single line method does work with the reversed() function, because it actually returns a list (almost!)