Skip to content
Related Articles

Related Articles

Improve Article

Python Program to Sort Words in Alphabetical Order

  • Difficulty Level : Basic
  • Last Updated : 23 Aug, 2021

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

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course

My Personal Notes arrow_drop_up
Recommended Articles
Page :