Languages
[Edit]
EN

Python - reverse words in a given string

0 points
Created by:
Antonina-Trejo
327

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']

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

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

Output:

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.

Cross technology - reverse words in a given 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.

❤️💻 🙂

Join