Reverse words in a given String in Python

Created with Sketch.

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 = "  quiz practice code"
Output : str = "code practice quiz  "

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.
# 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 = 'quiz practice code'
    print reverseWords(input)

Output:

 "code practice quiz  "

Leave a Reply

Your email address will not be published. Required fields are marked *