Python program to sort the words of string lexicographically

Published by user on

In this post, we will see how to sort the words of string lexicographically using python.
Algorithm
Step 1: Declare a String and store it in a variable.
Step 2: Split the string using split(“ ”) function with space as the parameter and store all the words in a list.
Step 3: Sort the all the words of list in lexicographical order using sort() function.
Step 4: Use a for loop to iterate over the words in the list and print the word while iterating.
Step 5: End.
Example

Input:  "welcome to the world of python programming"
Output: 
of
programming
python
the
to
welcome
world

Program

def sortStringInLexo(string):
        words = string.split()
        words.sort()
        for word in words:
                print( word )

if __name__ == '__main__':
        string = "welcome to the world of python programming"
        sortStringInLexo(string)

Output

of
programming
python
the
to
welcome
world
Categories: python