Program to reverse the position of each word of a given string in Python


Suppose we have a string of words delimited by spaces; we have to reverse the order of words.

So, if the input is like "Hello world, I love python programming", then the output will be "programming python love I world, Hello"

To solve this, we will follow these steps −

  • temp := make a list of words by splitting s using blank space
  • temp := reverse the list temp
  • return a string by joining the elements from temp using space delimiter.

Let us see the following implementation to get better understanding −

Example

 Live Demo

class Solution:
   def solve(self, s):
      temp = s.split(' ')
      temp = list(reversed(temp))
      return ' '.join(temp)
ob = Solution()
sentence = "Hello world, I love python programming"
print(ob.solve(sentence))

Input

"Hello world, I love python programming"

Output

programming python love I world, Hello

Updated on: 07-Oct-2020

416 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements