Introduction :
This is a python tutorial to reverse all words of a string. We will write one python program that will take one string as input and print out the new string by reversing all words in it.
Reversing a string is easy in python. For this problem, we will split the string and get all words, reverse all words, and join them back to get the final string. Thankfully, python provides all sorts of methods for splitting, joining and reversing a string and it takes only one line to do that.
I will solve this problem in two ways. First time, I will write all the steps and then I will show you how to do it in only one line.
Method 1 : sort, reverse and join :
I am dividing this example into steps : splitting the string, reversing the words and joining the reversed words back to a new string.
given_string = "Hello universe"
words = given_string.split()
reverse_words = []
for word in words:
reverse_words.append(word[::-1])
reverse_string = ' '.join(reverse_words)
print(reverse_string)
Here,
-
split() is splitting the string into words and it returns an array of words that we are storing in words variable.
-
reverse_words is the array to hold the reverse words. We are using one for loop to iterate over the words, reversing the words and joining them to a new string reverse_string
Method 2 : Using one line :
We can also write the above steps in only just one line :
given_string = "Hello universe"
reverse_string = ' '.join(word[::-1] for word in given_string.split())
print(reverse_string)
It will print the same output as the above example :
olleH esrevinu