In this article, we will learn about how to write python program to sort words in alphabetic order with examples.
Getting Started
The task is to sort words alphabetically using python program. For example,
Let’s say a = “Hello This is Rajeev From Tutorialwing”, then output should be “From Hello is Rajeev This Tutorialwing”
We can do above task in two ways
Using sort() Method
We can use sort() method of python list to write python program to sort words in alphabetic order as shown below –
def sortWords(input_string): words = input_string.split() words.sort(key=str.lower) sorted_string = " ".join(words) return sorted_string # Test the function input_string = input("Enter a string of words: ") sorted_string = sortWords(input_string) print("Ouput:", sorted_string)
Here,
- split() methods breaks the string of words into a list which contains all words as elements of that list.
- Now, sort() methods sorts the element alphabetically.
- After that, list is converted to string using join() method.
Enter a string of words: Hello This is Rajeev From Tutorialwing Output: From Hello is Rajeev This Tutorialwing
Using sorted() Method
There is another method sorted() which can be used to write python program to sort words in alphabetic order as shown below –
def sortWords(inputString): words = inputString.split() sortedWords = sorted(words, key=lambda word: word.lower()) sortedString = " ".join(sortedWords) return sortedString # Test the function inString = input("Enter a string of words: ") sortedString = sortWords(inString) print("Output:", sortedString)
Here,
- sorted() method takes list and a lambda function as input. Then, provides output as list of sorted words.
- After that, list of sorted words is converted into string using join() method.
Output:
Enter a string of words: Hello This is Rajeev From Tutorialwing Output: From Hello is Rajeev This Tutorialwing
Using sorted() Method and re Module
We can also use sorted() method with findall() method, to split words with punctuation, from re module to sort words in alphabetic order in python as shown below –
import re def sortWords(inputString): words = re.findall(r'\w+', inputString) sortedWords = sorted(words, key=str.lower) sortedString = " ".join(sortedWords) return sortedString # Test the function inString = input("Enter a string of words: ") sortedString = sortWords(inString) print("Output:", sortedString)
Output:
Enter a string of words: Hello This is Rajeev From Tutorialwing Output: From Hello is Rajeev This Tutorialwing
That’s how can we write python to sort words in alphabetic order using sort() method, sorted() method and re module.