Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Case insensitive sorting with sort(list, key=str.lower)

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

like image 705
nickg131 Avatar asked Dec 12 '13 05:12

nickg131


People also ask

What does STR lower mean?

Definition and Usage The lower() method returns a string where all characters are lower case.

What is key str lower Python?

Python String lower() method converts all uppercase characters in a string into lowercase characters and returns it.

How do you make a list case-insensitive in Python?

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.

How do you sort lower and upper case in python?

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.


1 Answers

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']
like image 139
RedBaron Avatar answered Oct 12 '22 07:10

RedBaron