Welcome, guest | Sign In | My Account | Store | Cart

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, 5 lines
1
2
3
4
5
def StringVersion( seq ):
    return '.'.join( ['%s'] * len( seq )) % tuple( seq )

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

2 comments

Drew Perttula 19 years, 10 months ago  # | flag

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.

Tim Keating (author) 19 years, 6 months ago  # | flag

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

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

Created by Tim Keating on Mon, 4 Feb 2002 (PSF)
Python recipes (4591)
Tim Keating's recipes (3)

Required Modules

  • (none specified)

Other Information and Tasks