Python: Reverse words in a string
Reverse words in a string.
Write a Python program to reverse words in a string.

Sample Solution:
Python Code:
# Define a function 'reverse_string_words' that takes a string 'text' as input.
# The function splits the input text into lines, reverses the words within each line, and returns the result.
def reverse_string_words(text):
for line in text.split('\n'):
return(' '.join(line.split()[::-1]))
# Call the 'reverse_string_words' function with the input "The quick brown fox jumps over the lazy dog.",
# reverse the words in the string, and print the result.
print(reverse_string_words("The quick brown fox jumps over the lazy dog."))
# Call the 'reverse_string_words' function with the input "Python Exercises.",
# reverse the words in the string, and print the result.
print(reverse_string_words("Python Exercises."))
Sample Output:
dog. lazy the over jumps fox brown quick The Exercises. Python
Flowchart:

For more Practice: Solve these Related Problems:
- Write a Python program to reverse the order of words in a sentence without reversing the characters of each word.
- Write a Python program to split a string into words, reverse the word order, and join them back into a sentence.
- Write a Python program to use list slicing to reverse the list of words obtained from a sentence.
- Write a Python program to implement a function that takes a sentence and returns it with the words in reverse order.
Python Code Editor:
Previous: Write a Python program to reverse a string.
Next: Write a Python program to strip a set of characters from a string.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics