We will develop a program to reverse a string in python using recursion. We can use the recursion technique to reverse a string in Python. A technique of defining the method/function that contains a call to itself is called recursion.
The recursive function/method allows us to divide the complex problem into identical single simple cases that can be handled easily. This is also a well-known computer programming technique: divide and conquer.
Example of reverse string:-
String: Know Program
Reverse String: margorP wonK
Reverse a String using Recursion in Python
We can also take the help of a function to reverse a string. A function is a block of code that performs a specific task. The len() function returns the string of items in an object. When the object is a string, the len() function returns the string of characters in the string.
# Python program to reverse a string using recursion
def findReverse(string): #user-defined function
# find reverse of string
if len(string) == 0:
return string
else:
return findReverse(string[1:]) + string[0]
# take inputs
string = 'Know program'
# calling function and display result
reverse = findReverse(string)
print('The reverse string is', reverse)
Output:-
The reverse string is margorp wonK
Reverse a String in Python using Recursion
In the previous program, inputs are hardcoded in the program but in this program, input will be provided by the user.
# Python program to reverse a string using recursion
def findReverse(string): #user-defined function
# find reverse of string
if len(string) == 0:
return string
else:
return findReverse(string[1:]) + string[0]
# take inputs
string = input('Enter the string: ')
# calling function and display result
reverse = findReverse(string)
print('The reverse string is', reverse)
Output for the input values test-case-1:-
Enter the string: recursion
The reverse string is noisrucer
Output for the input values test-case-2:-
Enter the string: Python
The reverse string is nohtyP
Output for the input values test-case-3:-
Enter the string: reverse
The reverse string is esrever
Output for the input values test-case-4:-
Enter the string: reverse a string
The reverse string is gnirts a esrever