natsort: TypeError when trying to sort a string of a number and a string

Python 3.3 and Python 3.4 fail to sort collections that contain strings that are also numbers:

>>> import natsort
>>> natsort.natsorted(('a', '1'))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/kwpolska/virtualenvs/nikola-py3/lib/python3.4/site-packages/natsort/natsort.py", line 247, in natsorted
    return sorted(seq, key=lambda x: natsort_key(key(x),
TypeError: unorderable types: float() < str()

This works just fine in Python 2.7.6.

via getnikola/nikola#1275 (cc @devurandom)

About this issue

  • Original URL
  • State: closed
  • Created 10 years ago
  • Comments: 18 (8 by maintainers)

Commits related to this issue

Most upvoted comments

You can use key(). For example, you can always compare tuples. The behaviour of sorted() is to compare elements left-to-right, and decide on the first one that’s not equal. So, to compare floats and strings, you could compare (‘string’, ‘1’) to (‘float’, 2.0). You can even generate the first element by using type()