You can specify a sorting key and use the sorting for tuples:
[(1,1),(1,2)]
: Tuples are sorted by 1st element, on equality by 2nd to nth:
unsorted = 'ABaB'
s = sorted(unsorted, key= lambda x:(x.lower(),x))
print(''.join(s)) # 'AaBB'
This ensures it is first sorted by the 'lower' character - grouping a
and A
together and then by the actual character afterwards so they occure sorted as well: ABaaAAaAaAAAB => AAAAAAAaaaaBB
Readups:
A simple key = str.lower
as suggested in the allegated dupe does not group A
to A
and a
to a
which would be nice to have for Prunnet squares
If you had them rather stay in order of occurence then grouping lower- and uppercase together, you can use:
unsorted = 'ABaaAAaAaAAAB'
s = sorted(unsorted, key=str.lower) # not by tuple, just by lower
print(''.join(s))
results in keeping the elements "in order":
AaaAAaAaAAABB # instead of AAAAAAAaaaaBB
and is described in case-insensitive list sorting, without lowercasing the result?