Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert version number to integer value?

Tags:

python

I am trying to convert application version numbers such as 5.3.0.1 (Android) and 5.3.0 (iOS) to integers in Python. The function should give output value as 5301 for Android and 530 for iOS.

I have written the following code but looking to make it smaller and better:

version = "5.3.0"
num = (version).split('.')

for i in num:
    version += i

print version

Suggest me some better options!

like image 307
Suraj Bhatia Avatar asked Nov 29 '22 09:11

Suraj Bhatia


1 Answers

Perhaps something a little more direct:

major, minor, patch = [int(x, 10) for x in version.split('.')]

The above will give you each component of the version number. You could also do something like:

l = [int(x, 10) for x in version.split('.')]
l.reverse()
version = sum(x * (100 ** i) for i, x in enumerate(l))

This will allow each component of the version number to vary between 0 and 99 (instead of just 0 through 9). It's a fairly common practice in C for recording version numbers.

If you really only want to handle components of the version being in the 0 to 9 range, simply change the 100 to a 10:

l = [int(x, 10) for x in version.split('.')]
l.reverse()
version = sum(x * (10 ** i) for i, x in enumerate(l))
like image 112
John Szakmeister Avatar answered Dec 05 '22 02:12

John Szakmeister