Languages
[Edit]
EN

Python - reverse words in a given string

0 points
Created by:
Dirask Community
6300

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

Python - string (popular problems)

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