Reverse words in a given String in Python

 

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.



# 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)

Output:

 "code practice quiz geeks"

No comments:

Post a Comment

Your feedback is highly appreciated and will help us to improve our content.