ActiveState Code

Recipe 111971: Format version numbers


It is common for Python modules to export their version number in list or tuple form. While it is simple to convert a dot-delimited string to a tuple, it's subtle and tricky to go the other way, particularly when you don't know how many "digits" there are. This recipe includes a pair of functions that convert between forms. Also handy for IP addresses!

Python
1
2
3
4
5
def StringVersion( seq ):
    return '.'.join( ['%s'] * len( seq )) % tuple( seq )

def TupleVersion( str ):
    return map( int, str.split( '.' ))

Comments

  1. 1. At 4:27 p.m. on 5 feb 2002, Drew Perttula said:

    what's the advantage of the %s interpolation? I don't see why the first function isn't just "return '.'.join(map(str,seq))". Perhaps there's a reason, but I can't think of it. Either way, you'll get len(seq) numbers in your result; zeros are handled correctly; and I can't see how speed/memory concerns would ever come into play for a function like this. (I suspect my version is faster, in any case.)

    Great example of calling join() on a literal string, by the way.

  2. 2. At 9:33 a.m. on 4 jun 2002, Tim Keating (the author) said:

    Um, because I didn't think of it? :-)

    You're right, though, that's probably a better approach and is most likely faster.

Sign in to comment