Python Reverse Words in a String
In this example, we will learn how to reverse the order of words in a string. For example, if the input string is "Hello World", the output should be "World Hello".
Examples
def reverse_words(s):
# Split the string into a list of words by spaces
words = s.split(' ')
# Reverse the list of words
words.reverse()
# Reassemble the reversed word list into a string
return ' '.join(words)
# Test the function
input_str = "Hello World"
output_str = reverse_words(input_str)
print(output_str)
# Split the string into a list of words by spaces
words = s.split(' ')
# Reverse the list of words
words.reverse()
# Reassemble the reversed word list into a string
return ' '.join(words)
# Test the function
input_str = "Hello World"
output_str = reverse_words(input_str)
print(output_str)
Code analysis:
s.split(' '): The input stringsis split by spaces into a list of wordswords。words.reverse(): Reverse the listwordsof the word order.' '.join(words): Reassemble the reversed word list into a string, with words separated by spaces.
Output result:
World HelloOther Extensions
Python3 Examples