EN
Python - reverse words in a given string
0
points
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 byseparator
.
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