I came across a strange Codecademy exercise that required a function that would take a string as input and return it in reverse order. The only problem was you could not use the reversed method or the common answer here on stackoverflow, [::-1]
.
Obviously in the real world of programming, one would most likely go with the extended slice method, or even using the reversed
function but perhaps there is some case where this would not work?
I present a solution below in Q&A style, in case it is helpful for people in the future.
You can reverse a String in several ways, without using the reverse() function. Using recursion − Recursion is the process of repeating items in a self-similar way. In programming languages, if a program allows you to call a function inside the same function, then it is called a recursive call of the function.
Reverse a string using for loop in Python for i in my_string: Now, since we are iterating, we will be using the iterating variable. We will concatenate the empty string str with the value of an iterating variable which will reverse the string one letter at a time.
Method 4: Reverse string in Python using an extended slice Extended slice offers to put a “step” field as [start, stop, step], and giving no field as start and stop indicates default to 0 and string length respectively, and “-1” denotes starting from the end and stop at the start, hence reversing a string.
You can also do it with recursion:
def reverse(text): if len(text) <= 1: return text return reverse(text[1:]) + text[0]
And a simple example for the string hello
:
reverse(hello) = reverse(ello) + h # The recursive step = reverse(llo) + e + h = reverse(lo) + l + e + h = reverse(o) + l + l + e + h # Base case = o + l + l + e + h = olleh
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With