Felka98
Felka98

Reputation: 109

Behavior of key optional parameter when using sorted()

s="String"
print(sorted(s,key=lambda x:x.upper()))

The output is ['g', 'i', 'n', 'r', 'S', 't']. However I don't seem to understand what is happening. I would like to sort the iterable s in a way that priority is given to lower case letters and at the end come upper case letters. So that the output is ['g', 'i', 'n', 'r', 't', 'S'].

Upvotes: 0

Views: 35

Answers (2)

Osman Mamun
Osman Mamun

Reputation: 2882

You can also use string module

from string import ascii_letters
print(sorted('String', key=lambda x: ascii_letters.index(x)))
#prints ['g', 'i', 'n', 'r', 't', 'S']

Upvotes: 1

blhsing
blhsing

Reputation: 106512

You can make the key function return a tuple of items you want the order to be based on instead:

sorted(s, key=lambda x: (x.isupper(), x))

Upvotes: 1

Related Questions