Python Principles

Reversing a string in Python

There are different ways to reverse a string in Python.

Using slicing

The usual way to reverse a string is to use slicing with a negative step:

>>> string = "hello world"
>>> string[::-1]
'dlrow olleh'

Breaking it down, string[:] means: "take the string from beginning to end", and string[::-1] means that the string should be taken one step at a time, adding -1 to the index after each step.

The final result is that the string gets reversed.

If you don't understand precisely what's going on, don't worry too much about it. Just put [::-1] after your string (or list, or tuple) to reverse it.

Using reversed

There is a built-in function named reversed that can give you an iterator over the string that runs in reverse. For example:

>>> string = "abc"
>>> for letter in reversed(string):
...     print(letter)
... 
c
b
a

However you cannot print this iterator directly, or you will see the reversed object:

>>> print(reversed("abc"))
<reversed object at 0x7f8222e12210>

Doing it manually

You can write your own function to reverse a string:

def reverse(string):
    result = ""
    index = len(string) - 1
    while index >= 0:
        result += string[index]
        index -= 1
    return result

print(reverse("hello"))

Running the code correctly prints olleh.

Improve your Python skills fast

The fastest way to learn programming is with lots of practice. Learn a programming concept, then write code to test your understanding and make it stick. Try our online interactive Python course today—it's free!

Learn more about the course

Want to get better at Python quickly? Try our interactive lessons today! Memberships are 100% FREE this week only!