Python | Sort words of sentence in ascending order

Given a sentence, sort it alphabetically in ascending order.


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.
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
    # 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
Sentence = "geeks for geeks"
# Print the sortedSentence



geeksforgeeks learn programming refer to
for geeks geeks

Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.

My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using or mail your article to See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

Improved By : shubham_singh

Article Tags :
Practice Tags :

Be the First to upvote.

Please write to us at to report any issue with the above content.