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:
xxxxxxxxxx
1
text = "dirask is cool"
2
3
list = text.split() # split by default separator (" ")
4
print("List before reverse:", list) # ['dirask', 'is', 'cool']
5
6
list.reverse()
7
print("List after reverse: ", list) # ['cool', 'is', 'dirask']
8
9
separator = " "
10
print(separator.join(list)) # cool is dirask
Output:
xxxxxxxxxx
1
List before reverse: ['dirask', 'is', 'cool']
2
List after reverse: ['cool', 'is', 'dirask']
3
cool is dirask