In Python, we can easily reverse words in a string in Python using the Python split(), reverse() and join() functions.
def reverseWords(string):
words = string.split()
words.reverse()
return " ".join(words)
print(reverseWords("this is a string with words"))
#Output:
words with string a is this
You can also use the split() function, slicing, and the join() function to reverse the words in a string with Python.
def reverseWords(string):
words = string.split()
return " ".join(words[::-1])
print(reverseWords("this is a string with words"))
#Output:
words with string a is this
When using string variables in Python, we can easily perform string manipulation to change the values or order of the characters in our string.
One such manipulation is to reverse the words in a string.
To reverse the words in a string, we can use the split() function to get a list of each word in the string, and then reverse the items in the list.
After reversing the list with the reverse() function or slicing, we then join the words together with join().
Below is an example function of how to reverse the words in a string using Python.
def reverseWords(string):
words = string.split()
words.reverse()
return " ".join(words)
print(reverseWords("this is a string with words"))
#Output:
words with string a is this
As mentioned above, you can also use slicing to reverse the list of words.
def reverseWords(string):
words = string.split()
return " ".join(words[::-1])
print(reverseWords("this is a string with words"))
#Output:
words with string a is this
Reversing Each Word in a String Using Python
If you are looking to reverse each word in a string, we can modify our examples from above slightly. Instead of reversing the order of the words, we will reverse the letters of each word.
In this case, we will split() the string to get each word, and then loop over each word and reverse it with string slicing.
After the loop is done, we will join the words back together.
Below is an example of how to reverse each word in a string with Python.
def reverseWords(string):
words = string.split()
for i in range(0,len(words)):
words[i] = words[i][::-1]
return " ".join(words)
print(reverseWords("this is a string with words"))
#Output:
siht si a gnirts htiw sdrow
Hopefully this article has been helpful for you to learn how to reverse the words in a string using Python.