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
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 Reversed = ", b))
Please enter your own : Tutorial Gateway The Original = Tutorial Gateway The Reversed = yawetaG lairotuT
It is another way of reversing a string using functions.
def StringReverse(str1): str2 = str1[::-1] return str2 a = input("Please enter your own : ") b = StringReverse(a) print("\nOriginal = ", a) print("After = ", b)
Please enter your own : Hello World! Original = Hello World! After = !dlroW olleH
In this code, we are doing string reverse by calling the function recursively.
def StringReverse(str1): if(len(str1) == 0): return str1 else: return StringReverse(str1[1:]) + str1 string = input("Please enter your own String : ") string2 = StringReverse(string) print("\nThe Original String = ", string) print("The Reversed String = ", string2)