Python @ DjangoSpin

PyPro #37 Reverse the Order of Words in a String

Buffer this pageShare on FacebookPrint this pageTweet about this on TwitterShare on Google+Share on LinkedInShare on StumbleUpon
Reading Time: 1 minutes

Reverse the order of words in a string in Python

Reverse the order of words in a string in Python

Python program to reverse the order of words in a string.

Reverse the Order of Words in a String

randomText = "this is some random text"

randomText.split()        # ['this', 'is', 'some', 'random', 'text']

randomText.split()[::-1]  # ['text', 'random', 'some', 'is', 'this']

' '.join(randomText.split()[::-1])    #'text random some is this'

If your original string has multiple lines, split it on the basis of the new line character i.e. \n.


See also:

Buffer this pageShare on FacebookPrint this pageTweet about this on TwitterShare on Google+Share on LinkedInShare on StumbleUpon

Leave a Reply