3.5. humansorted()

natsort.humansorted(seq, key=None, reverse=False, alg=0)

Convenience function to properly sort non-numeric characters.

Convenience function to properly sort non-numeric characters in a locale-aware fashion (a.k.a “human sorting”). This is a wrapper around natsorted(seq, alg=ns.LOCALE).

Warning

On some systems, the underlying C library that Python’s locale module uses is broken. On these systems it is recommended that you install PyICU. Please validate that this function works as expected on your target system, and if not you should add PyICU as a dependency.

Parameters:

seq : iterable

The sequence to sort.

key : callable, optional

A key used to determine how to sort each element of the sequence. It is not applied recursively. It should accept a single argument and return a single value.

reverse : {True, False}, optional

Return the list in reversed sorted order. The default is False.

alg : ns enum, optional

This option is used to control which algorithm natsort uses when sorting. For details into these options, please see the ns class documentation. The default is ns.FLOAT.

Returns:

out : list

The sorted sequence.

See also

index_humansorted
Returns the sorted indexes from humansorted.

Notes

You may find that if you do not explicitly set the locale your results may not be as you expect... I have found that it depends on the system you are on. To do this is straightforward (in the below example I use ‘en_US.UTF-8’, but you should use your locale):

>>> import locale
>>> # The 'str' call is only to get around a bug on Python 2.x
>>> # where 'setlocale' does not expect unicode strings (ironic,
>>> # right?)
>>> locale.setlocale(locale.LC_ALL, str('en_US.UTF-8'))
'en_US.UTF-8'

It is preferred that you do this before importing natsort. If you use PyICU (see warning above) then you should not need to do this.

Examples

Use humansorted just like the builtin sorted:

>>> a = ['Apple', 'Banana', 'apple', 'banana']
>>> natsorted(a)
[u'Apple', u'Banana', u'apple', u'banana']
>>> humansorted(a)
[u'apple', u'Apple', u'banana', u'Banana']