Python Program to sort the words in a string


February 12, 2022, Learn eTutorial
1085

In this simple python program, we need to sort the words in a string. It's an intermediate-level python program.

To understand this example, you should have knowledge of the following Python programming topics:

Explain the split and sort method in python?

In this simple python program, we need to sort the letters of a string in python. Sorting is a process that we need to arrange the words or letters in a specific order. Here we are using a split() method to split the words or letters into a list. Then use the sort() method to sort the words or letters in some order.

The default order is ascending; then, we use a for loop to print the letters of a string.

Split(): Split() the method in python language is used to split the words or letters into a list. We can use a max split in the split() method to get the max elements plus one. We can use anything as a parameter for splitting, so when that parameter is encountered, the split method will get activated like split(", "), the here split function will activate while ',' is encountered.

Sort (): sort() the method in python is used to sort the list elements. In default, the sort will do the arrangement in ascending order. to sort the words in descending order, we use a parameter to the sort method that is reverse. like sort(reverse=true). we can also sort the elements using user-defined keys using the sort() method. Sort(key=len) In this python program.

How sorting of a string done in python?

We accept the user input and save that into the variable str. Use both the functions 'split' to split the words to a list and apply the sort to that list to get sorted. Finally, use a for loop to print the sorted words list. 

ALGORITHM

STEP 1: Accept the string from the user using the input function in python language and save that to a variable.

STEP 2: Apply the split method in python to split the words into a list.

STEP 3: Apply the sort method to sort the list of elements in the default ascending order.

STEP 4: Use a for loop to print each element in the list.

Python Source Code

                                          str = input("Enter a string: ")  

words = str.split()  

words.sort()  
 
for word in words:  

   print(word)  
                                      

OUTPUT

Enter a string: a o e i u

a
e
i
o
u