Skip to content
Related Articles

Related Articles

Python Program to Sort Words in Alphabetical Order

Improve Article
Save Article
  • Difficulty Level : Basic
  • Last Updated : 18 Jul, 2022
Improve Article
Save Article

Given an input string, our task is to write a Python program to sort the words present in the string in alphabetical order.

Examples:

Input : “geeks for Geeks”

Output : “for geeks geeks”  

Input : “the Quick brown fox jumPs over the lazY Dog”

Output : “brown dog fox jumps lazy over quick the the”

Method 1: Using sorted()

sorted() is a predefined function in Python which returns the sorted list of any particular sequence.

Python3




# Python3 program to sort the words of a string in
# alphabetical order
 
# Function to sort the words in alphabetical order
def Func(S):
  W = S.split(" ")
  for i in range(len(W)):
     
      # convert all the words into lowercase
      W[i]=W[i].lower() 
  S = sorted(W)
  print(' '.join(S))
 
# Driver code
S = "the Quick brown fox jumPs over the lazY Dog"
 
# function call
Func(S)


Output:

brown dog fox jumps lazy over quick the the

Method 2: Using sort()

Python list sort() function can be used to sort a list in ascending, descending, or user-defined order. 

Python3




# Python3 program to sort the words of a
# string in alphabetical order
 
# Function to sort the words in alphabetical
# order
def F(S):
    W = S.split(" ")
    for i in range(len(W)):
        W[i] = W[i].lower()
    W.sort()
 
    # return the sorted words
    return ' '.join(W)
 
# Driver code
S = "GeekS for geEks"
print(F(S))


Output:

for geeks geeks

The time and space complexity of all the methods are the same::

Time Complexity: O(n*logn)

Auxiliary Space: O(n)


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!