Skip to content
Related Articles

Related Articles

Improve Article
Python | Sort words of sentence in ascending order
  • Difficulty Level : Basic
  • Last Updated : 22 Nov, 2019

Given a sentence, sort it alphabetically in ascending order.

Examples:

Input : to learn programming refer geeksforgeeks
Output : geeksforgeeks learn programming refer to

Input : geeks for geeks
Output : for geeks geeks

We will use built in library function to sort the words of the sentence in ascending order.
Prerequisites:
1. split()
2. sort() in Python
3. join()

  • Split the Sentence in words.
  • Sort the words alphabetically
  • Join the sorted words alphabetically to form a new Sentence.

Below is the implementation of above idea.






# Function to sort the words
# in ascending order
def sortedSentence(Sentence):
      
    # Splitting the Sentence into words
    words = Sentence.split(" ")
      
    # Sorting the words
    words.sort()
      
    # Making new Sentence by 
    # joining the sorted words
    newSentence = " ".join(words)
      
    # Return newSentence
    return newSentence
  
# Driver's Code
  
Sentence = "to learn programming refer geeksforgeeks"
# Print the sortedSentence
print(sortedSentence(Sentence))
  
Sentence = "geeks for geeks"
# Print the sortedSentence
print(sortedSentence(Sentence))

Output:

geeksforgeeks learn programming refer to
for geeks geeks

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with industry experts, please refer DSA Live Classes

My Personal Notes arrow_drop_up
Recommended Articles
Page :