Sort a string in lexicographic order python

You could use a 2-tuple for the key:

text='aAaBbcCdE'
sorted(text, key=lambda x: (str.lower(x), x))
# ['A', 'a', 'a', 'B', 'b', 'C', 'c', 'd', 'E']

The first element in the tuple, str.lower(x) is the primary key (making a come before B), while x itself breaks ties (making A come before a).


Do not use lambda functions when there's builtin ones for the job. Also never use the cmp argument of sorted because it's deprecated:

sorted(s, key=str.lower)

or

sorted(s, key=str.upper)

But that may not keep 'A' and 'a' in order, so:

sorted(sorted(s), key=str.upper)

that will and, by the nature of sorted the operation will be very fast for almost sorted lists (the second sorted).


cmp was the old way of doing this, now deprecated, but for posterity:

s='aAaBbcCdE'
sorted(s, lambda x,y: cmp(x.lower(), y.lower()) or cmp(x,y))