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.

  • Separate each word in given string using split() method of string data type in python.
  • Reverse the word separated list.
  • Print words of list, in string form after joining each word with space using ” “.join() method in python.
filter_none

edit
close

play_arrow

link
brightness_4
code

# Function to reverse words of string
  
def reverseWords(input):
      
    # split words of string separated by space
    inputWords = input.split(" ")
  
    # reverse list of words
    # suppose we have list of elements list = [1,2,3,4], 
    # list[0]=1, list[1]=2 and index -1 represents
    # the last element list[-1]=4 ( equivalent to list[3]=4 )
    # So, inputWords[-1::-1] here we have three arguments
    # first is -1 that means start from last element
    # second argument is empty that means move to end of list
    # third arguments is difference of steps
    inputWords=inputWords[-1::-1]
  
    # now join words with space
    output = ' '.join(inputWords)
      
    return output
  
if __name__ == "__main__":
    input = 'geeks quiz practice code'
    print reverseWords(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.



My Personal Notes arrow_drop_up


Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.