Python program to sort all words of a string in alphabetical order

Write a python program to sort all words of a String in Alphabetical order :

If you are not familiar with python string methods and loops, go through python string and python loop tutorials first.
To sort all words of a string, first we need to extract each word and store them somewhere. In this example, we are using split() method to split the string in words .This method returns a list with each word as elements of the list .Next, we are using sort() method on the list to sort all of its elements i.e. all words. Finally, we are using one for loop to print out all sorted words.

Example Program :

def sortAllWords(given_string):
    words_list = given_string.split()

    print ("Sorted string words are : ")

    for word in words_list:
        print(word," ")

user_string = input("Enter input string : ")

Example :

Enter input string :Ball apple boy Cat dog
Sorted string words are :

Leave a Reply