Reverse words in a given string in Python

File handling | Python Methods and Functions | String Variables

Examples:

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

This problem has an existing solution, please , refer to isalnum-isspace- join /> "" .join () in python.

# Function to reverse the words of the line

 

def reverseWords ( input ):

 

  # split the words of the line with a space

inputWords = input . split ( "" )

 

# reverse wordlist

# suppose we have a list of items list = [1,2,3,4],

  # list [0] = 1, list [1] = 2 and index -1 represents

# last list of items [-1] = 4 (equivalent to list [3] = 4)

# So inputWords [-1 :: - 1] is here we have three arguments

# first is -1, which means starting from the last element

# the second argument is empty, which means go to the end of the list

# third argument is step difference

  inputWords = inputWords [ - 1 :: - 1 ]

 

# now join words with spaces

output  = '' . join (inputWords)

 

  return output

 

if __name__ = = "__ main__" :

input = 'geeks quiz practice code'

  print reverseWords ( input )

Output:

 "code practice quiz geeks" 

This article contributed by Shashankom Mishra (Gullu) . If you are as Python.Engineering and would like to contribute, you can also write an article using contribute.python.engineering or by posting an article contribute @ python.engineering. See my article appearing on the Python.Engineering homepage and help other geeks.

Please post comments if you find anything wrong or if you'd like to share more information on the topic discussed above.





Tutorials