close
The Wayback Machine - https://web.archive.org/web/20200505163730/https://www.geeksforgeeks.org/reverse-words-given-string-python/amp/

Reverse words in a given String in Python

We are given a string and we need to reverse words of given string ?

Examples:

Input : str = "geeks quiz practice code"
Output : str = "code practice quiz geeks"



This problem has existing solution please refer Reverse words in a given String link. We will solve this problem in python. Given below are the steps to be followed to solve this problem.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Function to reverse words of string
  
def rev_sentence(sentence):
  
    # first split the string into words
    words = sentence.split(' ') 
  
    # then reverse the split string list and join using space
    reverse_sentence = ' '.join(reversed(words)) 
  
    # finally return the joined string
    return reverse_sentence  
  
if __name__ == "__main__":
    input = 'geeks quiz practice code'
    print rev_sentence(input)
chevron_right

Output:

 "code practice quiz geeks"

This article is contributed by Shashank Mishra (Gullu). If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.





Improved By : TanmayThaakur

Article Tags :
Practice Tags :