Case-insensitive Sorting By default, the sort() method sorts the list in ASCIIbetical order rather than actual alphabetical order. This means uppercase letters come before lowercase letters.
Sorting on the basis of the ASCII values differentiates the uppercase letters from the lowercase letters, and results in a case-sensitive order. Although the results in the Ascending order column might at first appear somewhat unpredictable, they are not.
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.
1 Answer. To do a case-insensitive search, you need to convert your target string and strings in the list to either lowercase or uppercase.
In Python 3.3+ there is the str.casefold
method that's specifically designed for caseless matching:
sorted_list = sorted(unsorted_list, key=str.casefold)
In Python 2 use lower()
:
sorted_list = sorted(unsorted_list, key=lambda s: s.lower())
It works for both normal and unicode strings, since they both have a lower
method.
In Python 2 it works for a mix of normal and unicode strings, since values of the two types can be compared with each other. Python 3 doesn't work like that, though: you can't compare a byte string and a unicode string, so in Python 3 you should do the sane thing and only sort lists of one type of string.
>>> lst = ['Aden', u'abe1']
>>> sorted(lst)
['Aden', u'abe1']
>>> sorted(lst, key=lambda s: s.lower())
[u'abe1', 'Aden']
>>> x = ['Aden', 'abel']
>>> sorted(x, key=str.lower) # Or unicode.lower if all items are unicode
['abel', 'Aden']
In Python 3 str
is unicode but in Python 2 you can use this more general approach which works for both str
and unicode
:
>>> sorted(x, key=lambda s: s.lower())
['abel', 'Aden']
You can also try this to sort the list in-place:
>>> x = ['Aden', 'abel']
>>> x.sort(key=lambda y: y.lower())
>>> x
['abel', 'Aden']
This works in Python 3 and does not involves lowercasing the result (!).
values.sort(key=str.lower)
In python3 you can use
list1.sort(key=lambda x: x.lower()) #Case In-sensitive
list1.sort() #Case Sensitive
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