Version Number Comparison Function
Fredrik Lundh
fredrik at pythonware.com
Fri Mar 25 11:02:31 EST 2005
"Keith" wrote:
> Is there a function for comparing version numbers?
>
> E.g.
>
> 0.1.0 < 0.1.2
> 1.876b < 1.876c
> 3.2.2 < 3.4
the following works for many common cases:
import re
def cmpver(a, b):
def fixup(i):
try:
return int(i)
except ValueError:
return i
a = map(fixup, re.findall("\d+|\w+", a))
b = map(fixup, re.findall("\d+|\w+", b))
return cmp(a, b) # -1 if a<b, 0 if a=b, 1 if a>b
>>> cmpver("0.1.0", "0.1.2")
-1
>>> cmpver("1.876b", "1.876c")
-1
>>> cmpver("3.2.2", "3.4")
-1
ymmv.
</F>
More information about the Python-list
mailing list