In this post, we will learn how to write a python program to reverse a string using recursion with a detailed explanation and algorithm.

With the help of the recursive function and slicing operator, we can easily reverse a String in python but before we jump into writing a program few programming concepts you have to know and that is:

  1. How to take user-input
  2. Slicing in Python
  3. Python Function &
  4. how recursive function work

Algorithm to Reverse a String Using Recursion

  • Define a function (def reverse_str(my_str)).
  • check if len(my_str) == 0 return my_str
  • else return a recursive function reverse_str(my_str[1:]) + my_str[0]

These three steps help you to reverse a string using recursion.

Source Code

def reverse_str(my_str):
   if len(my_str) == 0:
      return my_str
   else:
      return reverse_str(my_str[1:]) + my_str[0]

my_string = input('Enter your string:')
print(f"Given String: {my_string}")
print(f"reversed String: {reverse_str(my_string)}")

Output

Given String: allinpython
reversed String: nohtypnilla

Explanation

  1. The code starts with defining a function reverse_str that takes a string as input called my_str.
  2. Inside the function, there is an if statement that checks if the length of the my_str string is equal to zero then it will return my_str as it is.
  3. else the function calls itself but with a modified string my_str[1:]. This slicing removes the first character of the string.
  4. The result of the recursive call is then concatenated with the first character of the original my_str string (my_str[0]), and the result is returned.
  5. 2nd, 3rd and 4th steps are repeated until the length of the string is zero (len(my_str) == 0).
  6. after that, we take input from the user and store it in the my_string variable.
  7. Call the function reversed_str(my_string) and print the result.

Author

Hi, I'm Yagyavendra Tiwari, a computer engineer with a strong passion for programming. I'm excited to share my programming knowledge with everyone here and help educate others in this field.

Write A Comment