PythonMastery
Python programs · Strings · beginner

Reverse a string in Python

Reverse any text with the slice s[::-1]. Also shows how to reverse a string with a loop, and how to reverse the order of the words instead.

Python strings have no reverse() method, but a slice with a step of -1 reads the string from the last character to the first.

The program

python
text = input("Enter some text: ")
reversed_text = text[::-1]
print(reversed_text)

Typed in this example: Hello, World. Press Run to type your own.

output
Enter some text: Hello, World
dlroW ,olleH

How it works

With a loop

This version builds the result one character at a time. Each new character goes in front of what is already there:

python
text = "Python"
reversed_text = ""

for ch in text:
    reversed_text = ch + reversed_text

print(reversed_text)
output
nohtyP

Reverse the words, not the letters

To keep each word readable and change only their order, split the text into a list of words, reverse the list, and join it back together:

python
sentence = "learn it run it fix it"
words = sentence.split()
print(" ".join(reversed(words)))
output
it fix it run it learn

Learn the idea: Working with Strings, Loops: for, while, and the Pythonic Patterns

A longer explanation: How do I reverse a string in Python?