Login

How to compare two versions?

Author:
RafRaf
Posted:
November 23, 2013
Language:
Python
Version:
1.6
Tags:
comparison
Score:
0 (after 0 ratings)

ver_cmp('1.6.2', '1.6')

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
def ver_cmp(v1, v2):
    lst = map(lambda x, y: ((0 if not x else x), (0 if not y else y)),
              v1.split('.'), v2.split('.'))

    for num1, num2 in lst:
        if num1 != num2:
            if num1 > num2:
                return (1, 'greater')
            else:
                return (2, 'less')
    return (0, 'equal')

    # Example:
    #
    # >>> print ver_cmp('1.6.2', '1.6')
    # >>> (1, 'greater')

More like this

  1. . by jeremydw 5 years ago
  2. madslug by catellar 4 years ago
  3. templatetag by faruk 8 months, 1 week ago
  4. highlight text by nathantn 1 year ago
  5. watermark by dingdongquan 4 years, 8 months ago

Comments

syntaxsugar (on November 25, 2013):

Why not use distutils module?

from distutils.version import StrictVersion
>>> StrictVersion('1.6.2') > StrictVersion('1.6')
True

#

Please login first before commenting.