Learn Programming and technology with ease @ developerpublish.com

HomePythonPython Program to Reverse a String using Recursion

# 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

### You May Also Like

#### Python Program to Remove Duplicates from a Linked List

In this Python program, we will create a singly linked list and remove duplicate elements from it. A linked list...

#### Python Program to Solve the Celebrity Problem

This Python program solves the Celebrity Problem by finding a person who is known by everyone but does not know...

#### Python Program to Solve n-Queen Problem with Recursion

This Python program uses a recursive approach to solve the n-Queens problem. It explores all possible combinations of queen placements...