In this program, you’ll learn to sort the words in alphabetic order using for loop and display it.
To understand this example, you should have the knowledge of the following Python programming topics:
In this example, we illustrate how words can be sorted lexicographically (alphabetic order).
Source Code
# Program to sort alphabetically the words form a string provided by the user
my_str = "Hello this Is an Example With cased letters"
# To take input from the user
#my_str = input("Enter a string: ")
# breakdown the string into a list of words
words = [word.lower() for word in my_str.split()]
# sort the list
words.sort()
# display the sorted words
print("The sorted words are:")
for word in words:
print(word)
Output
The sorted words are: an cased example hello is letters this with
Note: To test the program, change the value of my_str.
In this program, we store the string to be sorted in my_str. Using the split() method the string is converted into a list of words. The split() method splits the string at whitespaces.
The list of words is then sorted using the sort() method, and all the words are displayed.
Related posts:
Python Machine Learning Cookbook - Practical solutions from preprocessing to Deep Learning - Chris A...
Python String isupper()
Python ascii()
Python Program to Find Factorial of Number Using Recursion
Python Namespace and Scope
Python Program to Split a List Into Evenly Sized Chunks
Python String swapcase()
Python List reverse()
Python setattr()
Python String casefold()
Python Set symmetric_difference_update()
Python frozenset()
Python Program to Measure the Elapsed Time in Python
Python iter()
Python Program to Iterate Over Dictionaries Using for Loop
Python float()
Python Program to Compute the Power of a Number
Python Program to Get the File Name From the File Path
Python Program to Check Whether a String is Palindrome or Not
Python String replace()
Python String isspace()
Python bool()
Python Program to Multiply Two Matrices
Introduction to Machine Learning with Python - Andreas C.Muller & Sarah Guido
Python Recursion
Python Program to Illustrate Different Set Operations
Python Variables, Constants and Literals
Python Program to Find ASCII Value of Character
Machine Learning Mastery with Python - Understand your data, create accurate models and work project...
Python locals()
Python Program to Count the Occurrence of an Item in a List
Python Tuple index()