Reputation: 109
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
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
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