Python Program to Sort Words in Alphabetic Order

Posted in

Python Program to Sort Words in Alphabetic Order
vinaykhatri

Vinay Khatri
Last updated on November 8, 2024

    Here in this article, we have provided a python source code that asks the user to enter a string, and in the output, it sorts the string words in the alphabetic order.

    Prerequisite Python Program to Sort Words in Alphabetic Order

    • Python Loop
    • Python Strings
    • Python String Methods

    In python, we have many in-built string methods which can be used to perform string manipulation.

    Steps

    • Ask the user to enter a string.
    • Use the split() method, which will convert the entered string into a list of words.
    • use the sort() method on the word list.
    • using the for loop print all the list sorted words.

    Python Program to Sort Words in Alphabetic Order

    Python Code

    string = input("Enter the String: ").lower()
    
    #split() method will create a list of string words.
    word_list = string.split()
    
    #use sort() method to sort the list element in lexographical order.
    word_list.sort()
    
    print(" -----------Sorted words of String are:--------------")
    for i in word_list:
        print(i)

    Output 1:

    Enter the String: hello!! welcome to techgeekbuzz
    -----------Sorted words of String are:--------------
    hello!!
    techgeekbuzz
    to
    welcome

    Output 2:

    -----------Sorted words of String are:--------------
    an
    example
    is
    of
    sorting
    this
    word

    People are also reading:

    Leave a Comment on this Post

    0 Comments