Sorting and spaces.
MRAB
python at mrabarnett.plus.com
Thu May 31 11:33:24 EDT 2018
On 2018-05-31 15:18, Tobiah wrote:
> I had a case today where I needed to sort two string:
>
> ['Awards', 'Award Winners']
>
> I consulted a few sources to get a suggestion as to
> what would be correct. My first idea was to throw them
> through a Linux command line sort:
>
> Awards
> Award Winners
>
> Then I did some Googling, and found that most US systems seem
> to prefer that one ignore spaces when alphabetizing. The sort
> program seemed to agree.
>
> I put the items into the database that way, but I had forgotten
> that my applications used python to sort them anyway. The result
> was different:
>
> >>> a = ['Awards', 'Award Winners']
> >>> sorted(a)
> ['Award Winners', 'Awards']
>
> So python evaluated the space as a lower ASCII value.
>
> Thoughts? Are there separate tools for alphabetizing
> rather then sorting?
>
You could split the string first:
>>> a = ['Awards', 'Award Winners']
>>> sorted(a, key=str.split)
['Award Winners', 'Awards']
If you want it to be case-insensitive:
>>> sorted(a, key=lambda s: s.lower().split())
['Award Winners', 'Awards']
More information about the Python-list
mailing list