Quantcast
Channel: Active questions tagged python - Stack Overflow
Viewing all articles
Browse latest Browse all 16862

How can I sort a string list in Python with two criterias at the same time?

$
0
0

Given I have a string list in Python:

list = ["   banana   ", "Cherry", "apple"]

I want to sort this list to be case insensitive AND ignore the whitespaces. So like this:

list = ["apple", "   banana   ", "Cherry"]

If I use this:

sorted(list, key=str.casefold)

I get this:

list = ["   banana   ", "apple", "Cherry"]

It's case insensitive, but the space character comes before the letters.

If I use this:

sorted(list, key=lambda x:x.replace('', ''))

I get this:

list = ["Cherry", "apple", "   banana   "]

It ignores the spaces but is not case-insensitive. I've tried to combine the two solutions, but I couldn't make it work. Is there a way to fix this easily and "merge" the two results?


Viewing all articles
Browse latest Browse all 16862


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>