How to Create a Function That Reverses a Sentence Word by Word
How to Create a Function That Reverses a Sentence Word by Word
How to Create a Function That Reverses a Sentence Word by Word
I want to reverse the order of words in a sentence. How can I do this in Python?
solveurit24@gmail.com Changed status to publish February 16, 2025
You can split the sentence into words, reverse the list of words, and then join them back into a string.
Code Example:
def reverse_sentence(sentence):
words = sentence.split()
reversed_words = words[::-1]
return ' '.join(reversed_words)
print(reverse_sentence("Hello world! How are you?")) # Output: "you? are How world! Hello"This function reverses the order of words in the input sentence.
solveurit24@gmail.com Changed status to publish February 16, 2025