3

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] 
0

2 Answers 2

5

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
Sign up to request clarification or add additional context in comments.

3 Comments

Hello, isn't for word in words: a for in / for statement.
@Kotchi It is a for loop
@Kotchi Added that as well
3

Try like this (Instead of recursive function split and join):

def myRev(string):
    return ' '.join(string[::-1].split()[::-1])

print(myRev("Hello World"))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.