Like we have see to sort words alphabetically in ascending order, we can also write python program to sort words in descending order alphabetically.
Getting Started
The task is to sort words in descending order alphabetically using python program. For example,
Let’s say a = “Hello This is Rajeev From Tutorialwing”, then output should be “Tutorialwing This Rajeev is Hello From”
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 descending order alphabetically as shown below –
def reverseSortWords(inString): words = inString.split() words.sort(key=str.lower, reverse=True) # Set reverse=True for reverse order revSortedString = " ".join(words) return revSortedString # Test the function inString = input("Enter a string of words: ") revSortedString = reverseSortWords(inString) print("Output:", revSortedString)
Here,
- split() methods splits the given string into a list which contains all words as elements of that list.
- Now, sort() methods sorts the element reverse order alphabetically. Note that we have passed reverse=True.
Enter a string of words: Hello This is Rajeev From Tutorialwing Output: Tutorialwing This Rajeev is Hello From
Using sorted() Method
Like sort() method, we can also use sorted() method to sort words alphabetically in reverse order.
def reverseSortWords(inString): words = inString.split() sortedWords = sorted(words, key=lambda word: word.lower(), reverse=True) # Set reverse=True for reverse order revSortedString = " ".join(sortedWords) return revSortedString # Test the function inString = input("Enter a string of words: ") revSortedString = reverseSortWords(inString) print("Output:", revSortedString)
Here,
- sorted() method accepts a list of words, a lambda function and whether to sort in ascending or descending order parameter. reverse=True is set to True if you want to sort words in reverse order.
Output:
Enter a string of words: Hello Rajeev! How are you ? Output: you Rajeev! How Hello are ?
Using sorted() Method and re Module
findall() method returns all words matching the given sequence. We can use it to get all words in given string of words.
import re def reverseSortWords(inString): words = re.findall(r'\w+', inString) sortedWords = sorted(words, key=str.lower, reverse=True) # Set reverse=True for reverse order revSortedString = " ".join(sortedWords) return revSortedString # Test the function inString = input("Enter a string of words: ") revSortedString = reverseSortWords(inString) print("Output:", revSortedString)
Output:
Enter a string of words: How are you? Output: you How are
That’s how can we write python to sort words in descending order alphabetically using sort() method, sorted() method and re module.
Learn more about python at official doc.