Strings · beginner
Python Program to Reverse a String
Reverse a string in Python with slicing [::-1], with reversed() and join(), and with a loop, and learn to reverse the order of words in a sentence.
- slicing
- reversed()
- str.join()
- str.split()
Python strings have no reverse() method, because strings cannot be changed in place. Instead you build a new, reversed string. The slice text[::-1] is the usual way: it reads the string from the end to the start.
The program shows three ways to reverse the characters and one way to reverse the order of words, which is a different task that people often confuse with it.
The program
text = "Hello, World"
print(text[::-1])
print("".join(reversed(text)))
result = ""
for ch in text:
result = ch + result
print(result)
sentence = "Python is fun"
print(" ".join(sentence.split()[::-1]))dlroW ,olleH
dlroW ,olleH
dlroW ,olleH
fun is PythonHow it works
- text[::-1] is a slice with no start, no end and a step of -1: it walks backwards through the whole string.
- reversed(text) gives the characters from last to first, and "".join() turns them back into a string.
- The loop puts each character in front of the result so far, so the first character ends up last. It is the slowest method but shows the idea.
- To reverse the words instead of the letters, split the sentence into a list of words, reverse the list and join it with spaces.
Watch it run line by line
Step through the for loop and watch result grow from the left: "H", "eH", "leH", … until the whole string is reversed.
“Visualize step by step” opens the program in the Python Compiler and records every step in your browser. Use the arrow keys to move forwards and backwards; changed variables are highlighted.
Common mistakes
- Calling text.reverse(): strings have no reverse method (lists do), so this raises AttributeError.
- Printing reversed(text) directly shows <reversed object at …> instead of the text.
- For text with emoji or accents made of several code points (such as a flag), reversing code points can split one visible character in two.
Try it yourself
- Reverse each word in place: "Python is fun" → "nohtyP si nuf".
- Write a recursive function: reverse(s) = reverse(s[1:]) + s[0].
Open the program in the Python Compiler, change it and press Run: there is nothing to install, and your code never leaves your browser.
Related examples
Browse all 25 Python examples, or write your own program in the online Python Compiler.