This concise, step-by-step guide shows you how to reverse the order of words in a string in Python.
The steps are:
- Split the string into individual words using the
split()
method. By default,split()
splits the string on whitespace, which separates the words. - Reverse the order of the words using slicing with a step of -1.
- 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)
print(reversed_text)
Output:
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!