How to sort list of strings alphabetically with upper and lower values?

Viewed 98

I have the following code:

v = ['zack', 'timor', 'Topher']
v.sort()
print(v)

['Topher', 'timor', 'zack']

What I want to get is:

['timor','Topher', 'zack']

which is the correct alphabetic order.

Basically it should ignore the difference between lower and upper letters. I can't just do lower() because ['timor','topher', 'zack'] is not the desired output.

in simple words I want it to compare with this rule: a=A, b=B, ... How can I do that?

3 Answers

You can specify a key function for sort. This would do it for this data:

v = ['zack', 'timor', 'Topher', 'Quark', "quark"]
v.sort( key= lambda x: x.lower())
print(v)

v = ['zack', 'timor', 'Topher', 'Quark', "quark"]
v.sort( key= lambda x: (x.lower(), x[0].isupper()))  # this will sort lower before upper
print(v)

['Quark', 'quark', 'timor', 'Topher', 'zack']  # keep original order
['quark', 'Quark', 'timor', 'Topher', 'zack']  # always lower before upper, only 1st char

But v.sort( key= lambda x: x.lower()) will stable sort - meaning it sorts by lowercasing and keeps the occurence order of the original list.

See

Add a key to your sorting, like:

def case_insensitive_sort(a):
    return a.lower()

v = ['zack', 'timor', 'Topher']
v.sort(key=case_insensitive_sort)
print(v)
Related