Python - reverse words in a given string

0 points
Created by:

In this article, we would like to show you how to reverse words in a string in Python.

To reverse words in a string we use:

  • split() method - to split the string into a list at the specified separator (default separator is white space " "),
  • reverse() method - to reverse and modify the original list,
  • join() method - to get a string with all the elements joined by separator.

Practical example:

text = "dirask is cool"

list = text.split()                  # split by default separator (" ")
print("List before reverse:", list)  # ['dirask', 'is', 'cool']

print("List after reverse: ", list)  # ['cool', 'is', 'dirask']

separator = " "
print(separator.join(list))          # cool is dirask


List before reverse: ['dirask', 'is', 'cool']
List after reverse:  ['cool', 'is', 'dirask']
cool is dirask
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

Python - string (popular problems)

Python - reverse words in string
Native Advertising
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂