w3resource

Python: Reverse words in a string


Reverse words in a string.

Write a Python program to reverse words in a string.

Python String Exercises: 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:

Flowchart: Reverse words in a string

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.

Go to:


Previous: Write a Python program to reverse a string.
Next: Write a Python program to strip a set of characters from a string.

Python Code Editor:

Contribute your code and comments through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.