This is my code so far, but I am trying to display olleH,dlroW instead of dlroW, olleH (Hello World). What is wrong with my code. Also i've seen examples that use for statements to reverse a string. But I would like to stick to if else statements (recursion).
def reverse_recursion(string):
if len(string) == 0:
return string
else:
return reverse_recursion(string[1:]) + string[0]
You can use [::-1] to reverse the string. So for it example could look like:
def reverse(string):
if len(string) == 0:
return string
else:
words = string.split()
new_string = ""
for word in words:
new_string += word[::-1] + " "
return new_string
Or if you would not like to use a for loop then you can use the following code:
def reverse(string):
if len(string) == 0:
return string
else:
words = string.split()
new_string = " ".join(list(map(lambda word: word[::-1], words)))
return new_string
Try like this (Instead of recursive function split and join):
def myRev(string):
return ' '.join(string[::-1].split()[::-1])
print(myRev("Hello World"))
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