Python Reverse the Words in a String
In this example we will learn how to reverse the order of words in a string. For example, given the input "Hello World", the output should be "World Hello".
Example
def
reverse_words
(
s
)
:
Split the string into a list of words by spaces
words
=
s.
split
(
' '
)
Reverse the list of words
words.
reverse
(
)
Join the reversed list of words back into a string
return
' '
.
join
(
words
)
Test the function
input_str
=
"Hello World"
output_str
=
reverse_words
(
input_str
)
(
output_str
)
Code analysis:
s.split(' '): Split the input stringsinto a list of words by spaceswords。words.reverse(): Reverse thewordsorder of the words in the list.' '.join(words): Join the reversed list of words back into a string, with the words separated by spaces.
Output result:
World Hello
Python3 Examples