Python: How to Reverse the Order of Words in a String

Updated: June 3, 2023 By: Goodman Post a comment

This concise, step-by-step guide shows you how to reverse the order of words in a string in Python.

The steps are:

  1. Split the string into individual words using the split() method. By default, split() splits the string on whitespace, which separates the words.
  2. Reverse the order of the words using slicing with a step of -1.
  3. Join the reversed words back into a string using the join() method, with a space as the separator.

Code example:

# Define a reusable function that reverses the words in a string
def reverse_words(string):
    words = string.split()
    reversed_words = words[::-1]
    reversed_string = ' '.join(reversed_words)
    return reversed_string

# Example usage
text = "Welcome to Sling Academy"
reversed_text = reverse_words(text)


Academy Sling to Welcome

Besides using slicing with [::-1] to reverse the elements in an array, you can also use the reversed() function like this:

reversed_words = reversed(words)

Reversing the order of words in a string in Python might be useful for tasks like text analysis, data preprocessing, transformations, and obfuscation.

The tutorial ends here. Happy coding & have a nice day!