Skip to content

Sort words in alphabetical order Python | Program example code

  • by

First, separate/break down the string by space into a list of words. Then use the sort method to sort words in alphabetical order in Python. In the last display the sorted words using for-loop.

Python Program to Sort Words in Alphabetic Order

Simple python example code:- The split() method splits the string at whitespaces.

my_str = "Hello world, Python tutorial"

words = my_str.split()

words.sort()

for word in words:
    print(word)

Output:

Sort words in alphabetical order Python

Input string is taken from user

input_str = input("Enter a string: ")

# breakdown the string into a list of words
words = input_str.split()

# sort the list
words.sort()

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

Output:

sort Input string is taken from user in Python

Do comment if you have any doubts and suggestions on this Python code.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

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