I have a list which contains strings representing animal names. I need to sort the list. If I use sorted(list), it will give the list output with uppercase strings first and then lowercase.
But I need the below output.
Input:
var = ['ant','bat','cat','Bat','Lion','Goat','Cat','Ant']
Output:
['ant', 'Ant', 'bat', 'Bat', 'cat', 'Cat', 'Goat', 'Lion']
The
sort()method and thesorted()function take a key argument:The function named in
keyis called for each value and the return value is used when sorting, without affecting the actual values:To sort
Antbeforeant, you’d have to include a little more info in the key, so that otherwise equal values are sorted in a given order:The more complex key generates
('ANT', False)forAnt, and('ANT', True)forant;Trueis sorted afterFalseand so uppercased words are sorted before their lowercase equivalent.See the Python sorting HOWTO for more information.