Home > Mobile >  reversing a sentence in python
reversing a sentence in python

Time:10-09

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

CodePudding user response:

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

CodePudding user response:

def reverse_sentence(sentence):
    return sentence.split(" ")[::-1]

print(reverse_sentence("hello how are you"))

Output:

❯ python3 pytmp.py
['you', 'are', 'how', 'hello']

First, we split the sentence into words. This is built-in and all we have to specify is the character to split on, which is a space.

Next we reverse the list. This utilizes 'slice notation.' Its full form is start:stop:step. I left start and stop empty, which means I will cover the entire list. I step backwards element-by-element with -1.

If you want just plain space-separated words:

def reverse_sentence(sentence):
    return " ".join(sentence.split(" ")[::-1])

print(reverse_sentence("hello how are you"))

Output:

❯ python3 pytmp.py
you are how hello

CodePudding user response:

If you want every single letter in the string reversed, you could try doing something like this:

def reverse(i):
 rev = [];                # it creates an array called rev 
 for letter in i:         # iterates for every letter in the string
    rev.append(letter);   # then appends the letter in the string into rev
 rev.reverse()            # .reverse() reverses the array
 return "".join(rev)      # and .join() brings the array into a string again

print(reverse("hello how are you"))

You'll get this as a result:

uoy era woh olleh

If you just want to reverse the words order, you could try this:

def reverse(i):
 rev = [];               # it creates an array called rev 
 for word in i.split():  # .split() splits the string into words
    rev.append(word);    # then appends the word in the string into rev
    rev.append(" ");     # .append() gets the whitespaces lost in .split()
 rev.reverse()           # .reverse() reverses the array
 return "".join(rev)     # and .join() brings the array into a string again
#test below

print(reverse("hello how are you"))

You'll get this as a result:

you are how hello

I'm not super into python but I hope I could help you somehow :D

  • Related