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')]
source
share