Python Reverse Words in a String

Document 对象参考手册Python3 Examples

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)

Code analysis:

  1. s.split(' '): The input stringsis split by spaces into a list of wordswords。
  2. words.reverse(): Reverse the listwordsof the word order.
  3. ' '.join(words): Reassemble the reversed word list into a string, with words separated by spaces.

Output result:

World Hello

Document 对象参考手册Python3 Examples

Other Extensions