split() turns a sentence into a list of words, and sorted() puts the list in alphabetical order. " ".join() turns the list back into one string.
The program
sentence = input("Enter a sentence: ") words = sentence.split() print("Default: ", " ".join(sorted(words))) print("Ignore case:", " ".join(sorted(words, key=str.lower)))
Typed in this example: Python was created by Guido van Rossum and released in 1991. Press Run to type your own.
Enter a sentence: Python was created by Guido van Rossum and released in 1991 Default: 1991 Guido Python Rossum and by created in released van was Ignore case: 1991 and by created Guido in Python released Rossum van was
How it works
- In the default order, every capital letter comes before every small letter, because strings are compared by character code. So "Guido", "Python" and "Rossum" come first. Digits come before all letters, so "1991" is first of all.
key=str.lowermakessorted()compare the small-letter version of each word. The words themselves are not changed: "Guido" is still printed with a capital G.- Punctuation stays attached to a word: "fun." is one word. To remove it first, see remove punctuation.
sorted(words, key=str.lower, reverse=True)gives the order from Z to A.
Each word only once
A set keeps only one copy of each item. Make the words lower case first, so "The" and "the" count as the same word:
sentence = "the cat and The dog and the bird" words = sentence.lower().split() unique = sorted(set(words)) print(unique) print(" ".join(unique)) print(len(words), "words,", len(unique), "different")
['and', 'bird', 'cat', 'dog', 'the'] and bird cat dog the 8 words, 5 different
sorted() accepts a set and returns a list, so the order is fixed again after the set. For more about sorted(), sort() and the key argument, see sort a list.