Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Reverse the Words in a String

Python Reverse the Words in a String

Document Object Reference Manual Python3 Examples

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

)

print

(

output_str

)

Code analysis:

  1. s.split(' '): Split the input string s into a list of words by spaces words。
  2. words.reverse(): Reverse the words order of the words in the list.
  3. ' '.join(words): Join the reversed list of words back into a string, with the words separated by spaces.

Output result:

World Hello

Document Object Reference Manual Python3 Examples