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

PythonServer Side ProgrammingProgramming

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 −


 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"


"Hello world, I love python programming"


programming python love I world, Hello
Published on 07-Oct-2020 17:11:44