How to Reverse a String in Python 3

John John (304)
2 minutes

There are multiple ways to reverse a string using Python 3. In this guide we're going to cover the extended slice operator and the reverse function. While they accomplish approximately the same thing, they each have a slightly nuanced use.

Posted in these interests:
h/python67 guides
h/code69 guides

Assuming we have the following string:

> x = "hello world"

we can reverse it like this:

> x[::-1]
'dlrow olleh'

The extended slice operator explained

The extended slice specifies a beginning, end, and step. Beginning is the place to begin in the sequence. End is the place to stop in the sequence. This allows you to slice off a portion of a sequence.

For the string

x = "hello world"

We can get the 2 - 5 characters like this:


Notice that this starts after the second character as the index starts at 0, and it ends after the fifth character producing:


To match our example, leaving the begining and end values empty means that we start at the beginning of the sequence and end at the end. Basically it includes the entire sequence.

"hello world"[::]


"hello world"

Step refers to how we will step through the sequence. If step is -1 then we are stepping through the sequence in reverse hitting every element. If step is 5, then we are moving through the sequence hitting every fifth element.

So using this:

"hello world"[::-1]

means that we include the entire string and step through backwards ultimately reversing the string.

The reversed function is a built-in function that takes an iterable and returns a "reversed" iterator.

Again, let's take our "hello world" string as an example:

> x = 'hello world'

We can reverse it like so:

> ''.join(reversed(x))
'dlrow olleh'

The reversed function explained

The reversed function takes an iterable and returns a reverse iterator. If you simply called reversed on a string, you'll see the iterator object:

> reversed('hello world')
<reversed at 0x10f583400>

This behaves like a normal iterator, so you can cast it as a list or use it in a for loop or use join to turn it into a string.

Flowers are nice. But these gifts will really make them smile!
Michael Michael (175)

Recently, I had a loved one who needed to stay in the hospital for an indeterminate amount of time, and I really wanted to make that hospital stay as enjoyable as possible with a unique gift.