Python Program to Reverse a String using Recursion

In this Python program, we will implement a recursive function to reverse a string. Recursion is a technique where a function calls itself to solve a smaller version of the problem. We will use this approach to reverse a given string.

Problem Statement

Given a string, we need to write a recursive function to reverse the string.

Python Program to Reverse a String using Recursion

def reverse_string(string):
    if len(string) == 0:
        return string
    else:
        return reverse_string(string[1:]) + string[0]


# Test the function
input_string = input("Enter a string: ")
reversed_string = reverse_string(input_string)
print("Reversed string:", reversed_string)

How its work

  1. The reverse_string function takes a string as input.
  2. In the base case, if the length of the string is 0, we return the string as it is (empty string).
  3. In the recursive case, we recursively call the reverse_string function on a smaller version of the string, obtained by excluding the first character, and then append the first character at the end.
  4. The function keeps calling itself until the length of the string becomes 0.
  5. Finally, the reversed string is returned.

Output

Python Program to Reverse a String using Recursion

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

In this Python program, we will create a singly linked list and remove duplicate elements from it. A linked list...
This Python program solves the Celebrity Problem by finding a person who is known by everyone but does not know...
This Python program uses a recursive approach to solve the n-Queens problem. It explores all possible combinations of queen placements...