Sorting / comparing version strings
Various ways to compare or sort version strings, eg
["1.1.2", "1.0.0", "1.3.3", "1.0.12", "1.0.2"], into natural order.
A common error with two-part version strings of the form
"1.3", "1.12" is to use a key function that converts them to floats; that won’t produce natural order.
Some of the linked answers use a key function like
lambda s: [int(u) for u in s.split('.')]; some use
distutils.version; and some use a regex so they can handle alphanumeric versions.
Note that some answers are not suitable for Python 3 because they use
lambda s: map(int, s.split('.'));
map returns a list in Python 2 but in Python 3 it returns an iterator.
Also, some Python 2 answers use
sort with a custom
cmp function instead of a
key function. That won’t work on Python 3, but the comparison functions may still be useful for simple comparisons.
cmp functions can be converted to
key functions using
functools.cmp_to_key, although that’s a slow, ugly hack. :)
‘How to compare “version-style” strings’ has an answer by davidism.