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.

Example

Below is a demonstration for the same −

 Live Demo

def reverse_string(my_string):
   if len(my_string) == 0:
      return my_string
   else:
      return reverse_string(my_string[1:]) + my_string[0]
my_str = str(input("Enter the string that needs to be reversed : "))
print("The string is :")
print(my_str)
print("The reversed string is :")
print(reverse_string(my_str))

Output

Enter the string that needs to be reversed : Williw
The string is :
Williw
The reversed string is :
williW

Explanation

  • A method named ‘reverse_string’ is defined, that takes a string as a parameter.
  • It checks the length of the string, and if it is not 0, then, the function is called again on all elements except the first element of the string, and the first element of the string is concatenated to the result of this fuction call.
  • Outside the function, the user is asked to enter a string as input.
  • The string is displayed on the console.
  • The recursion function is called by passing this string as a parameter.
  • It is displayed on the console as the output.

Updated on: 12-Mar-2021

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements