Python Program to Reverse a String Using Recursion

When it is required to reverse a string using recursion technique, a user-defined method is used along with recursion. The recursion computes output of small bits of the bigger problem, and combines these bits to give the solution to the bigger problem.

How Recursion Works for String Reversal

The recursive approach works by taking the first character and appending it to the reversed substring. The base case is when the string becomes empty.

Example

Below is a demonstration for the same ?

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

# Test with a sample string
my_str = "Python"
print("The string is:", my_str)
print("The reversed string is:", reverse_string(my_str))
The string is: Python
The reversed string is: nohtyP

How It Works

Let's trace through the recursion with "ABC" as an example ?

def reverse_string(my_string):
    print(f"Called with: '{my_string}'")
    if len(my_string) == 0:
        print("Base case reached")
        return my_string
    else:
        result = reverse_string(my_string[1:]) + my_string[0]
        print(f"Returning: '{result}'")
        return result

# Trace the execution
text = "ABC"
print("Tracing reverse_string('ABC'):")
reversed_text = reverse_string(text)
print(f"Final result: {reversed_text}")
Tracing reverse_string('ABC'):
Called with: 'ABC'
Called with: 'BC'
Called with: 'C'
Called with: ''
Base case reached
Returning: 'C'
Returning: 'CB'
Returning: 'CBA'
Final result: CBA

Alternative Recursive Approach

Another way to implement recursive string reversal using an index parameter ?

def reverse_string_indexed(text, index=0):
    if index == len(text):
        return ""
    return reverse_string_indexed(text, index + 1) + text[index]

# Test the alternative approach
sample = "Hello"
print("Original string:", sample)
print("Reversed string:", reverse_string_indexed(sample))
Original string: Hello
Reversed string: olleH

Key Points

  • Base case: When the string length is 0, return empty string
  • Recursive case: Reverse the substring and append the first character
  • Time complexity: O(n) where n is the string length
  • Space complexity: O(n) due to recursive call stack

Conclusion

Recursive string reversal demonstrates the power of breaking down problems into smaller subproblems. The base case handles empty strings, while the recursive case processes one character at a time, building the reversed string from the end backward.

Updated on: 2026-03-25T17:36:15+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements