Why does Python sort put upper case items first?

后端 未结 3 2146
暗喜
暗喜 2020-12-11 05:37

Not looking for a work around. Looking to understand why Python sorts this way.

>>> a = [\'aaa\',\'Bbb\']
>>> a.sort()
>>> print(a         


        
3条回答
  •  一向
    一向 (楼主)
    2020-12-11 06:06

    str is sorted based on the raw byte values (Python 2) or Unicode ordinal values (Python 3); in ASCII and Unicode, all capital letters have lower values than all lowercase letters, so they sort before them:

    >>> ord('A'), ord('Z')
    (65, 90)
    >>> ord('a'), ord('z')
    (97, 112)
    

    Some locales (e.g. en_US) will change this sort ordering; if you pass locale.strxfrm as the key function, you'll get case-insensitive sorts on those locales, e.g.

    >>> import locale
    >>> locale.setlocale(locale.LC_COLLATE, 'en_US.utf-8')
    >>> a.sort(key=locale.strxfrm)
    >>> a
    ['aaa', 'Bbb']
    

提交回复
热议问题