How do I make the sorted function ignore some characters?

Viewed 443

I'm pretty new to python and was sorting through an array of strings. But I noticed a problem for my use case.

Take an array like the following:

["C", "CSS", "CSA", "C-SHARP"]

When I pass it through sorted(), it becomes:

["C-SHARP", "C", "CSA", "CSS"]

Is there a way I can ignore some characters, which for my case is the '-' character, so that the result becomes:

["C", "CSA", "C-SHARP", "CSS"]

2 Answers

Sort using a lambda which removes non alphanumeric characters:

inp = ["C", "CSS", "CSA", "C-SHARP"]
out = sorted(inp, key=lambda x: re.sub(r'[^A-Za-z0-9]+', '', x))
print(out)

This prints:

['C', 'CSA', 'C-SHARP', 'CSS']

You can replace "-" with "" while sorting. This won't affect the final list.

sorted(your_list, key=lambda item: item.replace("-", ""))

Result

['C', 'CSA', 'C-SHARP', 'CSS']
Related