Program to display the words of string from longest to shortest

Program to display the words of string from longest to shortest

Problem statement

Python program to accept a string from the user, divide the string into words and display the words of string from longest to shortest.

Video Tutorial

Steps

First, accept a string from the user using the input statement and store it into a string variable. say str1 in this case.

Divide the string into words using the split() function, store the result that is a list of words into a words list.

Create an empty list to store the word and its length as a tuple. say t in this case.

Use for loop and get one word from the words list in each iteration.

Append the tuple (length of word and word) into list t.

Once all words are appended to the list t, sort the list t in reverse order.

As we need to sort the words from the longest to shortest sort in reverse order.

See also  Download and install Python 3

Next, create a res list to store the words from the list t, use for loop to get the elements of t. The element of t is actually a tuple, hence use multiple assignments in for loop.

Finally, append the word to the res list. Once all words are appended display the res list.

Solution: Program to display the words of string from longest to shortest

#Suppose you have a string and you want to sort the words of string from longest to shortest:

str1 = input("Enter the string: ")
print ("String is: ", str1)
words = str1.split()
print ("Words in string are: ", words)
t = list()

for word in words:
    t.append((len(word), word))
t.sort(reverse=True)

res = list()
for length, word in t:
    res.append(word)
print("Words in string sorted from longest to shortest:", res)

Output

Enter the string: HSIT Nidasoshi VTU Belagavi
String is:  HSIT Nidasoshi VTU Belagavi
Words in string are:  ['HSIT', 'Nidasoshi', 'VTU', 'Belagavi']
Words in string sorted from longest to shortest: ['Nidasoshi', 'Belagavi', 'HSIT', 'VTU']

Summary:

This tutorial discusses how to write a Python program to accept a string from the user. Divide the string into words and display the words of string from longest to shortest. If you like the tutorial share it with your friends. Like the Facebook page for regular updates and YouTube channel for video tutorials.

See also  Classes and Objects in Python

Leave a Comment

Your email address will not be published. Required fields are marked *