Problem: Write a program in Python to sort all words of a sentence or string in dictionary (Alphabetical) order.

Example:

Input:  Welcome to Pencil Programmer Official Website
Output: Official Pencil Programmer Website Welcome to 

Solution:

The idea is to split the whole sentence into a list of words and sort the list in alphabetical order using the inbuilt sort() method.

After sorting the list, we will concatenate the words to form a new sentence.

sentence = input("Enter a english sentence: ")

words = sentence.split()
words.sort()

newSentence = ""
for x in words:
    newSentence += x + " "
    
print(newSentence)

Output:

Enter a english sentence: Welcome to Pencil Programmer Official Website
Official Pencil Programmer Website Welcome to

Leave a Reply

eleven − 3 =