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!
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With