Q:

Write a python program to sort words in alphabetical order

0

Write a python program to sort words in alphabetical order

In this exercise, you will learn how to sort words in alphabetic order using Python. Python is a high-level, open source, general-purpose programming language. It enables us to write clear, logical applications for small and large tasks. It has a set of useful libraries, packages, and functions that minimise the use of code in our day-to-day life. A simple Python programming task is sorting a list of words or items in alphabetical order. You may need to add this feature to sort a list of items in e-commerce application development.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Python sort words in a list in alphabetical order

Python provides a predefined function sorted() that returns a sorted list of the specified list. It accepts both object types, numbers and strings. Numbers are sorted numerically, and strings are sorted alphabetically. But, we can not provide a list containing both.

sorted(iterable, key, reverse)

Here, the iterable is the required parameter that contains either sort, list, dictionary, or tuple. The key is the optional parameter, which is a function to decide the order parameter. The reverse is also optional, which accepts a boolean value. False will sort ascending, True will sort descending.

Python Alphabetic Order Example

In the given example, we have sorted words in ascending order-

vehicles = ("car","bike","truck","motorcycle","train")
x = sorted(vehicles)
print(x)

Output of the above code -

(env) c:\python37\Scripts\projects>test.py
['bike', 'car', 'motorcycle', 'train', 'truck']

Here is the other alphabetic order example in descending order-

vehicles = ("car","bike","truck","motorcycle","train")
x = sorted(vehicles, reverse=True)
print(x)

Output of the above code -

(env) c:\python37\Scripts\projects>test.py
['truck', 'train', 'motorcycle', 'car', 'bike']

Python Sort Words in a String in Alphabetical Order

In the given example, we have written a program to take a string input from the user and sort the words in that given string 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()

# display the sorted words  
print("The sorted words are:")
for word in words:
   print(word)

 Output of the above code0- 

Enter a string: John is smaller than Smith
The sorted words are:
John
Smith
is
smaller
than

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Python Exercises, Practice Questions and Solutions

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Write a python program to sum all the numbers in a... >>
<< Write a program to read two numbers and print thei...