user14514627
user14514627

Reputation:

How to reverse strings in python by word

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] 

Upvotes: 3

Views: 564

Answers (2)

wind
wind

Reputation: 2451

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

Upvotes: 5

wasif
wasif

Reputation: 15528

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

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

print(myRev("Hello World"))

Upvotes: 3

Related Questions