def rreverse(s):
    if s == "":
        return s
    else:
        return rreverse(s[1:]) + s[0]

(Very few people do heavy recursive processing in Python, the language wasn't designed for it.)

Answer from Fred Foo on Stack Overflow
Top answer
1 of 8
39
def rreverse(s):
    if s == "":
        return s
    else:
        return rreverse(s[1:]) + s[0]

(Very few people do heavy recursive processing in Python, the language wasn't designed for it.)

2 of 8
37

To solve a problem recursively, find a trivial case that is easy to solve, and figure out how to get to that trivial case by breaking the problem down into simpler and simpler versions of itself.

What is the first thing you do in reversing a string? Literally the first thing? You get the last character of the string, right?

So the reverse of a string is the last character, followed by the reverse of everything but the last character, which is where the recursion comes in. The last character of a string can be written as x[-1] while everything but the last character is x[:-1].

Now, how do you "bottom out"? That is, what is the trivial case you can solve without recursion? One answer is the one-character string, which is the same forward and reversed. So if you get a one-character string, you are done.

But the empty string is even more trivial, and someone might actually pass that in to your function, so we should probably use that instead. A one-character string can, after all, also be broken down into the last character and everything but the last character; it's just that everything but the last character is the empty string. So if we handle the empty string by just returning it, we're set.

Put it all together and you get:

def backward(text):
    if text == "":
        return text
    else:
        return text[-1] + backward(text[:-1])

Or in one line:

backward = lambda t: t[-1] + backward(t[:-1]) if t else t

As others have pointed out, this is not the way you would usually do this in Python. An iterative solution is going to be faster, and using slicing to do it is going to be faster still.

Additionally, Python imposes a limit on stack size, and there's no tail call optimization, so a recursive solution would be limited to reversing strings of only about a thousand characters. You can increase Python's stack size, but there would still be a fixed limit, while other solutions can always handle a string of any length.

๐ŸŒ
freeCodeCamp
freecodecamp.org โ€บ news โ€บ python-reverse-string-string-reversal-in-python-explained-with-code-examples
Python Reverse String โ€“ String Reversal in Python Explained with Examples
November 10, 2021 - But since Python strings are immutable, you cannot modify or reverse them in place. In Python, there are a few different ways you can do this. And this tutorial will teach you how you can use string slicing, built-in methods, and recursion to reverse strings.
๐ŸŒ
Medium
medium.com โ€บ @fridahwatetu โ€บ reversing-a-string-in-python-using-recursion-21346d959f68
Reversing a String In Python Using Recursion | by Fridah | Medium
August 8, 2023 - Reversing a String In Python Using Recursion string = "Hello World" def reversing_string(string): if (string == ""): return "" return reversing_string(string[1:]) + string[0] str โ€ฆ
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ dsa โ€บ reverse-a-string-using-recursion
Print reverse of a string using recursion - GeeksforGeeks
March 6, 2025 - Input: s = "Reverse a string Using Recursion" Output: "noisruceR gnisU gnirts a esreveR" Explanation: After reversing the input string we get "noisruceR gnisU gnirts a esreveR".
๐ŸŒ
Sanfoundry
sanfoundry.com โ€บ python-program-reverse-string-using-recursion
Reverse a String in Python - Sanfoundry
June 19, 2023 - In this approach, we use recursion to reverse a string by repeatedly swapping the first and last characters. ... Here is source code of the Python Program to reverse a string using recursion.
๐ŸŒ
Flexiple
flexiple.com โ€บ python โ€บ python-reverse-string
Reverse String In Python - Flexiple
To reverse a string in Python using recursion, employ a function that recursively chops off the first character and appends it to the end.
๐ŸŒ
Real Python
realpython.com โ€บ reverse-string-python
Reverse Strings in Python: reversed(), Slicing, and More โ€“ Real Python
July 31, 2023 - Here, you first compute the index of the last character in the input string by using len(). The loop iterates from index down to and including 0. In every iteration, you use the augmented assignment operator (+=) to create an intermediate string that concatenates the content of result with the corresponding character from text. Again, the final result is a new string that results from reversing the input string. ... You can also use recursion to reverse strings.
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ python-program-to-reverse-a-string-using-recursion
Python Program to Reverse a String Using Recursion
The recursion computes output of small bits of the bigger problem, and combines these bits to give the solution to the bigger problem. ... 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 ...
Find elsewhere
๐ŸŒ
YouTube
youtube.com โ€บ watch
Reverse The Given String Using Recursion | Python Programs | Interview Question And Answer - YouTube
In this Python programming video series we will learn how to reverse the given string using recursion.Program 01:def reverse_str(str1): if str1 == "": ...
Published ย  February 1, 2021
๐ŸŒ
GitHub
github.com โ€บ arnab132 โ€บ Reverse-String-using-Recursion-in-Python
GitHub - arnab132/Reverse-String-using-Recursion-in-Python: Implementation of Reverse String using Recursion in Python
If not equal to 0, the reverse function is recursively called to slice the part of the string except the first character and concatenate the first character to the end of the sliced string.
Author ย  arnab132
๐ŸŒ
BeginnersBook -
beginnersbook.com โ€บ home โ€บ python examples โ€บ python program to reverse a string using recursion
Python program to reverse a String using Recursion
June 6, 2018 - # Program published on https://beginnersbook.com # Python program to reverse a given String # Using Recursion # user-defined recursive function def reverse(str): if len(str) == 0: return str else: return reverse(str[1:]) + str[0] mystr = "BeginnersBook" print("The Given String is: ", mystr) ...
๐ŸŒ
Team Treehouse
teamtreehouse.com โ€บ community โ€บ reverse-string-using-recursion
Reverse string using recursion (Example) | Treehouse Community
June 18, 2015 - def reverse(t): print("t = " + t) if t == "": print("t is empty") return t else: return reverse(t[1:]) + t[0] print(reverse('hello world')) ... t = hello world t = ello world t = llo world t = lo world t = o world t = world t = world t = orld ...
๐ŸŒ
Career Karma
careerkarma.com โ€บ blog โ€บ python โ€บ python reverse string: a step-by-step guide
Python Reverse String: A Step-By-Step Guide | Career Karma
December 1, 2023 - You can reverse a string in Python using slicing or the reversed() method. A recursive function that reads each character in a string and reverses the entire string is another common way to reverse a string.
๐ŸŒ
Reddit
reddit.com โ€บ r/askcomputerscience โ€บ trying to reverse a string using recursion, why is my program not working?
Trying to reverse a string using recursion, why is my program not working? : r/AskComputerScience
February 28, 2020 - I'm also not sure if the O(1) recursive like solution works in python because, as far as I know, python does not support tail call optimization. ... class Solution { public: void reverseString(vector<char>& s) { reverse(s, 0, s.size() - 1); } void reverse(vector<char>& s,int left,int right){ // stop when all characters have been swapped if(left> right){ return; } // swap first and last unreversed characters char temp = s[left]; s[left] = s[right]; s[right] = temp; // call the function on the next unreversed characters reverse(s, left + 1, right - 1); } };
Top answer
1 of 3
5

They are not adding up immediately until recursion reaches to final expression. Here, what is happening on each step:

"5" + backwards("1234")
"5" + "4" + backwards("123")
"5" + "4" + "3" + backwards("12")
"5" + "4" + "3" + "2" + backwards("1")
"5" + "4" + "3" + "2" + "1" + backwards("")
"5" + "4" + "3" + "2" + "1" + ""
"54321"

Basically you are constructing a chain of return statements (aka call stack), they concatenate at the very end into "54321".

In above computation, I omitted return keywords. For e.g. "5" + "4" + backwards("123") looks like return "5" + (return "4" + backwards("123")) in reality.

2 of 3
1

You are correct in what text[-1] and text[:-1] give you. I think where you're getting tripped up is on the recursive aspect of it, which is the tricky part.

When you're working on recursive stuff it helps not to overthink it. I know that most of programming requires you to understand every little nuance of your code but recursion is different. If you try to think through a recursive function's call stack in your head you'll just get confused. Human brains aren't like computers. Our stacks can only get about three levels deep before we lose track.

So for this problem the way you want to think about it is something like this:

"To reverse a string, you simply take the last character and put it at the beginning of the reversified version of the remaining characters."

It seems like a nonsense statement because it's defined in terms of itself, but that's precisely what recursion is, a function that is defined in terms of itself.

So for you question, text[-1] gives you the last item in the list and text[:-1] give you the remaining characters.

As an example, if your list is [1, 2, 3, 4] then evaluating each recursive call would go something like this:

backwards([1, 2, 3, 4])

evaluates to

4 + backwards([1, 2, 3])

which evaluates to

4 + 3 + backwards[1, 2])

which evaluates to

4 + 3 + 2 + backwards([1])

which evaluates to

4 + 3 + 2 + 1

When I first answered this question, I thought the function you listed didn't work and you wanted one that did, so I threw one together real quick. When I wrote it, I literally typed out the quote I listed above into my text editor then wrote out the python code (which looks just like the one you have posted). I didn't step through each call in my head I just typed out the sentence then wrote some code that implemented that sentence.

Recursion takes some getting used to but once you kind of get how think recursively you can apply it to all kinds of problems.

Another example that might be a bit more straight forward would be a recursive function that sums up all the numbers in a list.

sum([1, 2, 3, 4]) => 10

So the statement for this would be

To sum a list, add the first item in the list to the sum of the remaining elements in the list.

The python would look like this:

def sum(a):
    if len(a) == 0:
        return 0
    else:
        return a[0] + sum(a[1:])
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ reverse-string-python-5-different-ways
How to reverse a String in Python - GeeksforGeeks
Looping & List comprehension provides more control over the reversal process. stack approach is least suitable here, but it helps in understanding the data structures & algorithmic thinking and problem-solving. ... A string is a sequence of characters. Python treats anything inside quotes as a string.
Published ย  November 21, 2024
๐ŸŒ
Javatpoint
javatpoint.com โ€บ how-to-reverse-a-string-in-python
How to reverse a string in Python - Javatpoint
Write Python Program to Find Uncommon Characters of the Two Strings ยท Write Python Program to Recursively Remove All Adjacent Duplicates ยท Write the Python Program to Reverse the Vowels in the Given String ยท How to use Pass statement in Python ยท Recursion in Python ยท