Python Program to Sort Words in Alphabetical Order
In this example, we will write a program to take a string input from the user and sort the words in that given string in alphabetical order. To better understand this example, make sure you have knowledge of the following tutorials:-
Python Program to Sort Words in Alphabetical Order
input_str = input("Enter a string: ") # breakdown the string into a list of words words = input_str.split() # sort the list words.sort() print("The sorted words are:") for word in words: print(word)
The output of the above program is:-
Enter a string: My Name is John Doe
The sorted words are:
Doe
John
My
Name
is
The sorted words are:
Doe
John
My
Name
is
Program Explanation:
The sorting of string into alphabetical order is quite straightforward. The input string is taken from user and broken down into words using the split() method of string. Sort() method sorts the words in alphabetical order which is then displayed using a for a loop.