I have a module designed to allow users to enter 10 words, then alphabetize them, and display them. Just using the sort functions puts capitalized words first, so i used sort(list, key=str.lower) but the output is still incorrect. Code, and error, below:
def words_function():
words = [input("Enter 10 words, one at a time: ") for i in range(10)]
sorted(words, key=str.lower)
print("Alphabetized, your words are: ", words)
userSearch = input("What word would you like to search for?")
if userSearch in words:
print("Found!")
else:
print("Not Found!")
words_function()
And it outputs this order: ['Aardvark', 'coke', 'Desk', 'Zippy', 'zappy', 'Television', 'brothel', 'book', 'Dad', 'dog']
Which, last time I took English, wasn't alphabetical =p. What else do I need to add to my sort, or change, to make it come out in proper alphabetical order, ignoring if the word is lower case or capital, and just sorting in based on alphabetization?
Aardvark, book, brothel, coke, Dad, Desk, dog, Television, zappy, Zippy
Definition and Usage The lower() method returns a string where all characters are lower case.
Python String lower() method converts all uppercase characters in a string into lowercase characters and returns it.
Approach No 1: Python String lower() Method This is the most popular approach to case-insensitive string comparisons in Python. The lower() method converts all the characters in a string to the lowercase, making it easier to compare two strings.
By default, the sort() method sorts the list in ASCIIbetical order rather than actual alphabetical order. This means uppercase letters come before lowercase letters. This causes the sort() function to treat all the list items as if they were lowercase without actually changing the values in the list.
sorted
returns the sorted list. It does not modify the list in place. You'll have to store the sorted list somewhere
words = sorted(words, key=str.lower)
On python 2.6
>>> words= ['Aardvark', 'coke', 'Desk', 'Zippy', 'zappy', 'Television', 'brothel', 'book', 'Dad', 'dog']
>>> sorted(words,key=str.lower)
['Aardvark', 'book', 'brothel', 'coke', 'Dad', 'Desk', 'dog', 'Television', 'zappy', 'Zippy']
>>> words
['Aardvark', 'coke', 'Desk', 'Zippy', 'zappy', 'Television', 'brothel', 'book', 'Dad', 'dog']
>>> words = sorted(words,key=str.lower)
>>> words
['Aardvark', 'book', 'brothel', 'coke', 'Dad', 'Desk', 'dog', 'Television', 'zappy', 'Zippy']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With