November 2, 2017
Reverse string using recursion in Python
Question
Write a recursive function in Python to reverse a string of characters.
Solution
The reverse of a string is the concatenation of the first character and the reverse of the remaining characters in the string. Recall that the first character is put on the right side when doing the concatenation.
Code
The following is a suggested solution in Python.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
# Recursive function to reverse a string (Str) def reverseString(Str): # Base case when the string is one character if len(Str) == 1: return Str # Otherwise do the concatenation return reverseString(Str[1:]) + Str[0] # Input string Str = "123456789" # Call the function print "The reverse of '{}' is '{}'".format(Str, reverseString(Str)) |
If you run the code above, you should get the output below:
1 |
The reverse of '123456789' is '987654321' |
If you have questions or comments, please use the comments section below .Thanks for visiting.