Q&A library Python

How do I reverse a string in Python?

Python Beginner reversedslicingstrings

Short answer

Use the slice with a step of minus one, written as text[::-1]. It is the shortest and fastest way, and works because strings support the same slicing as lists.

The short version

Reverse a string with the slice text[::-1]. That is a slice from start to end with a step of minus one, so it walks the characters backwards. It is the standard, fastest and most idiomatic method, and it works because strings support slicing just like lists.

The slice

text = "hello"
print(text[::-1])   # "olleh"

The three parts of a slice are start, stop and step. Leaving start and stop empty means "the whole thing", and a step of -1 means "move backwards one at a time".

The readable alternative

If the slice looks cryptic to your team, reversed with join spells out the intent. It is slightly slower but perfectly clear.

"".join(reversed("hello"))   # "olleh"

reversed returns an iterator of characters, and "".join(...) glues them back into a string with no separator.

Why strings need rebuilding

Strings are immutable, so you cannot reverse one in place; every method here produces a new string and leaves the original unchanged. That is why there is no text.reverse() method as there is for lists.

A caution about characters versus code points

For plain text these methods are fine. But reversing by code point can break text that uses combining characters or emoji made of several code points, because the pieces get separated. This rarely matters for everyday strings, but if you are reversing arbitrary user text containing such characters, be aware that a naive reversal can produce mojibake. For ordinary words and identifiers, text[::-1] is exactly right.

Reversing the words instead of the characters

A related task is reversing word order rather than letters. Split on spaces, reverse the list, and join back.

"the quick fox".split()[::-1]        # ['fox', 'quick', 'the']
" ".join("the quick fox".split()[::-1])   # "fox quick the"

Be clear about which you want: reversing characters and reversing word order are different jobs.

Need this solved on your own data?

The library is free and always will be. When the problem is bigger than an answer, we take on the work.

Start a project