How to Sort Words in Alphabetical Order in Python


In this example, we will learn how to alphabetically sort a sequence of the hyphen-separated words.

Source Code

#! /usr/bin/env python3
# -*- coding: utf-8 -*-

print("Please input a sequence of letters separated by hyphens: ")
str = input()
strList = [s for s in str.split('-')]
strList.sort()
hyphen = "-"
print("After sorting: ")
print(hyphen.join(strList))

Output:

Please input a sequence of letters separated by hyphens: 
p-d-e-a-g-f-r
After sorting: 
a-d-e-f-g-p-r
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
Advertisement