Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

reversing a sentence in python

Need to use a for loop to reverse a sentence, we are also creating a function, here is what I have, it wont print, I feel like it should work but it wont, hoping it is a minor typo.

# reverse 
def reverse(text):
 rev = ""
 for i in text.split(" "):
    rev = i + rev
 return rev
#test below
rev = "hello how are you"
print(reverse(rev))

I need it reversed by word not character
I edited this slightly, I don’t think I fixed it

UPDATE this is close but prints it without spaces "youarehowhello" I cant figure out how to print with spaces

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

def reverse(sentence): 
   res = "" 
   for word in sentence.split(" "): 
        res = word + " " + res 
   return res 
# test below 
rev = "hello how are you" 
print(reverse(rev)) # you are how hello
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading