In this post, we will learn how to reverse a string using recursion using Python Programming language.
So, without further ado, let’s begin this tutorial.
Python Program to Reverse a String Using Recursion
# Python Program to Reverse a String Using Recursion def reverse(string): if len(string) == 0: return string else: return reverse(string[1:]) + string[0] # Asking for input a = str(input("Enter a string: ")) # Displaying output print("Reversed String: ", reverse(a))
Output
Enter a string: Spiderman
Reversed String: namredipS
def reverse(string): if len(string) == 0: return string else: return reverse(string[1:]) + string[0]
We have declared a recursive function named reverse. Then, we pass the string as an argument.
If the length of the string equals to 0, then the string is returned. If not 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 function.
# Asking for input a = str(input("Enter a string: "))
Then, the user is asked to enter a string.
# Displaying output print("Reversed String: ", reverse(a))
Finally, we call the recursive function and print the reverse number using print() statement.
Conclusion
I hope after going through this post, you understand how to reverse a string using recursion using Python Programming language.
If you have any doubt regarding the program, feel free to contact us in the comment section. We will be delighted to guide you.
Also Read: