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.
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)
- split() is splitting the string into words and it returns an array of words that we are storing in words variable.
- reversewords_ 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 reversestring_
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 :
- Python program to convert a list to string
- Python tutorial to calculate the sum of two string numbers
- Python program to pad zeros to a string
- Convert string to float in python
- Python example program to split a string at linebreak using splitlines
- Python program to check if two strings are an anagram or not