Sort: how to handle a special character other than an alphabetic character in Python 2?

At present time, Python sort(), and sorted()gives me the following:

>>> sorted(a, reverse=True, key=lambda s: re.sub('[\[\]]', '', s).lower())
[u'Category123', u'[Cat@123]', u'CAT']

But I need:

[u'[Cat@123]', u'Category123', u'CAT']

I need characters like: !@#$%^&*can be sorted as more than alphabetic characters. Thank.

EDIT: In addition to the accepted answer, I realized that this would solve my problem:

>>> sorted(a, reverse=True, key=lambda s:s.upper())
[u'[Cat@123]', u'Category123', u'CAT']
+4
source share
1 answer

Return two values ​​from the function key, the first will be a logical check if any of the special characters in the string exist or not, and the second is the substitution string itself.

>>> def func(s):
    subbed = re.sub('[\[\]]', '', s).lower()
    return any(c in '!@#$%^&*' for c in s), subbed
...
>>> lst = [u'Category123', u'[Cat@123]', u'CAT']
>>> sorted(lst, reverse=True, key=func)
[u'[Cat@123]', u'Category123', u'CAT']

So, essentially, we are sorting something like this:

>>> new_lst = [(False, 'category123'), (True, 'cat@123'), (False, 'cat')]
>>> sorted(new_lst, reverse=True)
[(True, 'cat@123'), (False, 'category123'), (False, 'cat')]
+5
source

Source: https://habr.com/ru/post/1599620/


All Articles