Reverse words in a string using python

In this article, we shall see how to reverse words in a string using python. The mistake most often we make is we would reverse the entire string and not the words. Consider the following string.

“Welcome to python coders blog”

When somebody asks us to reverse the words what we have to is,

blog coders python to Welcome

and not reversing the entire string like this.

golb sredoc nohtyp ot emocleW

This is somewhat a complicated thing to in other programming languages. But in case of python it is extremely easy as it has various built-in string methods. We will be using the following two string methods to achieve this task in hand.

  1. split()
  2. join()

Let us also see what both of these methods does.

split()

The split() method would split a string based on any separator if given. Otherwise, it would split the string with a whitespace character by default.

split() method python

The output of the above code is,

['Welcome', 'to', 'python', 'coders', 'blog']

As we can see the sentence is split into individual words. Since no separator is given the string is split based on the whitespaces.

join()

The next method is the join() method. The join() method will take a list of strings or other iterators and combine/join the individual strings to a single string.

The join method will take the separator also based on which it will separate the words while joining them. I have given whitespace as my separator in the following example.

join method python

The output of the above code is,

Welcome to python coders blog

So pretty you would have guess what we are going to with these two methods.

How to reverse words in a string?

We will be following these three steps. They are

  1. Get the words of the string in a list.
  2. Reverse the list. (This way the words are reversed)
  3. Join the words in the list.

Let us write the code following these three steps.

That is all we have to do. The output of the above code is,

blog coders python to Welcome

This is what we need and look how easily we did this in five lines using python. Actually 3 lines if you exclude the print statement and the initial string.

Conclusion

I hope this article is helpful. If you have any queries regarding this program leave them in the comments below. Happy coding!