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
Original string: Python Reversed string: nohtyP
How it works
reversed_textstarts as an empty string.- The loop visits each character of
textfrom left to right. ch + reversed_textputs the new character in front of what has been collected so far, so the last character ends up first.- After the loop,
reversed_textholds the whole string backwards.
Other ways to write it
Using slicing
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()
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.
Related programs
All Python programs · CBSE class 12 practical file · Python exercises