How to reverse an order of words using python?

In this article, we will see how to reverse an order of words using a python programming language.

For example, if a given word is “Python is great language” then the output would be “language great is python”.

Also, if you would like to know that how to reverse a string letter by letter and store the result in the list or another string read our article here.

For example “Python is great language” then the output would be “egaugnal taerg si nohtyp”.

So now let us see that how will we reverse each word of string and display output in another list or string.

Code: –

Reverse words in a given String in Python

Output: –

how to reverse words in a given String in Python

Explanation

  1. We have taken a variable name string1 and inside in we have passed a string ‘Python is great language’
  2. We have taken another variable named l and applied a split method of string.

The split() method separates the string by taking the separator inside its round bracket and outputs the result in the form of a list.

And that is exactly what we have done on line 2, and we have provided “ ” an empty space as a separator so whenever an empty space is encountered the string is separated and value is added to the list.

  1. Now our output is in l variable and that to in list form. There is a reverse method inside the list which reverses each element of a list, and that is what we have done on line number 3.
  2. The output of l is printed on line number 4 and you can see the output below the image it is in a list format and reverse order.

Now to display output in string format we have used the same code.

  1. We have taken another variable named string2 which is completely empty and after = that is the assignment operator we have used a join() method of string which is a built-in method only for string.

join() method takes an iterable object as an argument it can be a list or another string and joins them to a new string (in this case it joins to string2 variable). But before joining we have specified the value using which it should join, and that value is an empty space in this case.

  1. We have printed the output on line number 6th. As you can see below image string is revered and the output is in string format.

Conclusion

This code was to reverse the order of words and print output in a list or string

If you want to see how to reverse the order of each letter and print output in the list or string read this article. Click here.

Waqar Khan

Hello, everyone, I am Waqar Khan. I have done my B.tech in Computer Science. I love to write about Computer Informational blogs. Before write I did proper research on it. Hope you like our blogs. Thank you.

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *