Editor

Python Program to Reverse a String

Beginner · Strings

Reversing a string means putting its characters in the opposite order, so "Python" becomes "nohtyP". This program builds the reversed string one character at a time with a loop, and the alternatives show the shorter ways Python offers.

Program

reverse_a_string.py
text = "Python" # or: text = input("Enter a string: ")
reversed_text = ""
for ch in text:
reversed_text = ch + reversed_text # put each character in front
print("Original string:", text)
print("Reversed string:", reversed_text)
Output
Original string: Python
Reversed string: nohtyP

How it works

  1. reversed_text starts as an empty string.
  2. The loop visits each character of text from left to right.
  3. ch + reversed_text puts the new character in front of what has been collected so far, so the last character ends up first.
  4. After the loop, reversed_text holds the whole string backwards.

Other ways to write it

Using slicing

Using slicing
text = "Python"
reversed_text = text[::-1]
print("Reversed string:", reversed_text)
Output
Reversed string: nohtyP

A slice with a step of -1 walks the string from the end to the start. This is the usual way to reverse a string in Python.

Using reversed() and join()

Using reversed() and join()
text = "Python"
reversed_text = "".join(reversed(text))
print("Reversed string:", reversed_text)
Output
Reversed string: nohtyP

reversed() gives the characters in reverse order and "".join() glues them back into one string.

Try it yourself

Reverse the order of the words in "I love Python" instead of the letters.

Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.

All Python programs · CBSE class 12 practical file · Python exercises