In this Python program, we will learn how to reverse a string. There are various ways to reverse a string in python. Here we use 4 ways to reverse a string using loops and by using a recursive function.
Here is the source code of the program to reverse a string in Python.
# Python Program to Reverse a String using For Loop
# Take the Input From the User
string = input("Enter the String: ")
string2 = ''
for i in string:
string2 = i + string2
print("\nThe Original String = ", string)
print("The Reversed String = ", string2)
Enter the String: Tutorialsrack
The Original String = Tutorialsrack
The Reversed String = kcarslairotuT
# Python Program to Reverse a String Using While Loop
# Take the Input From the User
string = input("Enter the String: ")
string2 = ''
i = len(string) - 1
while(i >= 0):
string2 = string2 + string[i]
i = i - 1
print("\nThe Original String = ", string)
print("The Reversed String = ", string2)
Enter the String: Tutorialsrack.com
The Original String = Tutorialsrack.com
The Reversed String = moc.kcarslairotuT
# Python Program to Reverse a String By Using Recursive Function
# Define a Recursive Function
def StringReverse(str1):
if(len(str1) == 0):
return str1
else:
return StringReverse(str1[1:]) + str1[0]
# Take the Input From the User
string = input("Enter the String: ")
string2 = StringReverse(string)
print("\nThe Original String = ", string)
print("The Reversed String = ", string2)
Enter the String: Tutorialsrack.com is an online learning website
The Original String = Tutorialsrack.com is an online learning website
The Reversed String = etisbew gninrael enilno na si moc.kcarslairotuT
# Python Program to Reverse a String Another Way to Reverse a String
# Define a Function
def StringReverse(str1):
str2 = str1[::-1]
return str2
# Take the Input From the User
string = input("Enter the String: ")
string2 = StringReverse(string)
print("\nThe Original String = ", string)
print("The Reversed String = ", string2)
Enter the String: Tutorialsrack.com is an online learning website
The Original String = Tutorialsrack.com is an online learning website
The Reversed String = etisbew gninrael enilno na si moc.kcarslairotuT
Comments