Write a Python program to Reverse String using For Loop, while loop, and Functions with an example.
Python Program to Reverse String using For Loop
This program allows the user to enter any sentence. Next, this Python code reverses the string using For Loop.
st1 = input("Please enter your own : ") st2 = '' for i in st1: st2 = i + st2 print("\nOriginal = ", st1) print("After = ", st2)
Please enter your own : Coding
Original = Coding
After = gnidoC
From the above reverse a string program screenshot you can observe that, word is Coding.
For Loop First Iteration: for i in st1
=> for C in Coding
str2 = C + st2=> C + ”
Second Iteration: for o in Coding
st2 = o + C => oC
Do the same for the remaining iterations. Please refer String article to understand them in Python.
using While Loop
This Python string reverse program using while loop is the same as above. However, we just replaced the For Loop with While Loop. Here, len function is used to find length to total characters in a sentence.
a = input("Please enter your own : ") b = '' i = len(a) - 1 while(i >= 0): b = b + a[i] i = i - 1 print("\nThe Original = ", a) print("The Inverted = ", b))
Please enter your own : Tutorial Gateway
The Original = Tutorial Gateway
The Inverted = yawetaG lairotuT
using Function
It is another way of reversing a string using functions.
def StrInverse(str1): str2 = str1[::-1] return str2 a = input("Please enter your own : ") b = StrInverse(a) print("\nOriginal = ", a) print("After = ", b)
Please enter your own : Hello World!
Original = Hello World!
After = !dlroW olleH
using Recursion
In this code, we are doing string reverse by calling the function recursively.
def StrInverted(str1): if(len(str1) == 0): return str1 else: return StrInverted(str1[1:]) + str1[0] str2 = input("Please enter your own : ") str3 = StrInverted(str2) print("\nThe Original = ", str2) print("The Inversed = ", str3)
