Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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] 

2 Answers

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
like image 74
Abhigyan Jaiswal Avatar answered Mar 07 '26 15:03

Abhigyan Jaiswal


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

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

print(myRev("Hello World"))
like image 25
programmer365 Avatar answered Mar 07 '26 17:03

programmer365



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!