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 stri
New answer for Python 3, I'd like to add two points:
That is:
var = ['ant','bat','cat','Bat','Lion','Goat','Cat','Ant']
var.sort(key=str.casefold)
(which sorts in-place) and now:
>>> var
['ant', 'Ant', 'bat', 'Bat', 'cat', 'Cat', 'Goat', 'Lion']
Or, to return a new list, use sorted
>>> var = ['ant','bat','cat','Bat','Lion','Goat','Cat','Ant']
>>> sorted(var, key=str.casefold)
['ant', 'Ant', 'bat', 'Bat', 'cat', 'Cat', 'Goat', 'Lion']
Why is this different from str.lower
or str.upper
? According to the documentation:
Casefolding is similar to lowercasing but more aggressive because it is intended to remove all case distinctions in a string. For example, the German lowercase letter
'ß'
is equivalent to"ss"
. Since it is already lowercase,str.lower()
would do nothing to'ß'
;casefold()
converts it to"ss"
.