Python program to reverse a string using loop
In this tutorial, we will learn how to reverse a string using loop in Python.
You are given a string. Your task is to reverse the string using loop.
There are many inbuilt methods to reverse a string in Python but we will learn it using loop in this tutorial.
METHOD 1: Reverse a string
Initially, we take an empty variable named res to store the reversed string. We’ll iterate through each character one by one and then append it to the starting of the resultant string to get the final result.
Here we have a function named reverse_string() which will accept the input string and return the reversed string.
def reverse_string(string): res = "" for s in string: res = s + res return res input_string = input("Enter the string to reverse: ") reversed_string = reverse_string(input_string) print(f"Reversed string is: {reversed_string}")
OUTPUT:
Enter the string to reverse: CodeSpeedy made learning easy Reversed string is: ysae gninrael edam ydeepSedoC
METHOD 2:
This method is similar to the above one, only difference is that we’ll use indexing to get the desired output. We’ll iterate through each character one by one from right to left and then append it to the resultant string to get the final result.
Here we have a function named reverse_string() which will accept the input string and return the reversed string.
def reverse_string(string): res = "" for i in range(len(string)-1, -1, -1): res += string[i] return res input_string = input("Enter the string to reverse: ") reversed_string = reverse_string(input_string) print(f"Reversed string is: {reversed_string}")
OUTPUT:
Enter the string to reverse: CodeSpeedy made learning easy Reversed string is: ysae gninrael edam ydeepSedoC
We’ve successfully learned to reverse a string in Python, simplifying the solution for better understanding. I hope you found the process enjoyable!
Leave a Reply