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

Time:11-12

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?

CodePudding user response:

Just chain the calls

values = ["   banana   ", "Cherry", "apple"]
print(sorted(values, key=lambda x: x.replace(' ', '').casefold()))
# ['apple', '   banana   ', 'Cherry']

To only discard spaces at the beginning and end, I'd suggest str.strip

print(sorted(values, key=lambda x: x.strip().casefold()))

CodePudding user response:

You can use str.strip() for removing spaces from beginning and end of string and str.lower().

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

res = sorted(lst, key=lambda x: x.strip().lower())

# we can use `.casefold()` by thanks `@wjandrea`
# res = sorted(lst, key=lambda x: x.strip().casefold())

print(res)

Output:['apple', ' banana ', 'Cherry']

  • Related