Sort list of strings ignoring upper/lower case

后端 未结 3 955
青春惊慌失措
青春惊慌失措 2020-12-05 02:38

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

3条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-05 03:21

    New answer for Python 3, I'd like to add two points:

    1. Use str.casefold for case-insensitive comparisons.
    2. Use the method directly instead of inside of a lambda.

    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".

提交回复
热议问题