PythonMastery

How do I reverse a string in Python?

text[::-1] returns the string reversed: a slice with a step of -1, walking from the end. ''.join(reversed(text)) does the same and reads more plainly.

Slice it with a step of -1.

python
word = "stressed"
print(word[::-1])
output
desserts

Why [::-1] works

A slice is [start:stop:step]. Leave out start and stop and you get the whole string; a step of -1 walks through it backwards. Other steps work the same way:

python
letters = "abcdefgh"

print(letters[::2])     # every second letter
print(letters[::-2])    # every second letter, from the end
print(letters[2:5])     # positions 2, 3 and 4
output
aceg
hfdb
cde

The readable alternative

reversed() returns the characters in reverse order, and "".join glues them back into a string. Longer, but someone new to Python can read it:

python
word = "stressed"
print("".join(reversed(word)))
output
desserts

reversed(word) on its own is not a string; printing it shows <reversed object at 0x...>. The join is what turns it back into text.

A common use: palindromes

python
def is_palindrome(text):
    letters = [c.lower() for c in text if c.isalnum()]
    return letters == letters[::-1]

print(is_palindrome("Never odd or even"))
print(is_palindrome("Python"))
output
True
False

Slicing works on lists too, as you can see. Removing spaces and punctuation first is what makes "Never odd or even" count.

Reversing words, not letters

python
sentence = "the quick brown fox"
print(" ".join(sentence.split()[::-1]))
output
fox brown quick the

One limit worth knowing: [::-1] reverses code points, not what you see as letters. An accent stored as a separate combining mark, or an emoji built from several parts like a family or a flag, comes apart when reversed. For names and plain words it never matters; for user-generated text with emoji, it can.

Go deeper: Working with Strings, Python Slicing Cheat Sheet

More short answers

all questions