Python Program to Reverse String

Write a Python program to Reverse String using For Loop, while loop, and Functions with an example.

Reverse String using For Loop

This program allows the user to enter any sentence. Next, this 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

You can observe from the above program screenshot 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.

Python Program to reverse a String using While Loop

This program using the while loop is the same as above. However, we just replaced the For Loop with While Loop. Here, the len function is used to find the length of the total characters in a sentence.

# using a while loop
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

We are doing string reverse in this code by calling the function recursively.

# using recursive function
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)
Python Program to Reverse String 4