Working with strings

A quantity can be created from a string expression, but not all libraries understand the same syntaxis and vocabulary

Some python libraries to work with physical quantities, as pint, are very efficient parsing strings. And some other probably not. And in addition, it is probable that not all of them use the samy syntaxis. With PyUnitWizard a unique parser and syntaxis can be used not matter the desired form of the quantity. Let’s show how the methods pyunitwizard.string_to_quantity() and pyunitwizard.string_to_unit() work:

import pyunitwizard as puw
puw.configure.load_library(['pint', 'openmm.unit'])
puw.configure.set_default_form('openmm.unit')
puw.quantity('2 litres + 20 dL')
Quantity(value=4.0, unit=liter)
puw.convert('2 newtons per square meter', parser='pint')
Quantity(value=2.0, unit=newton/(meter**2))
puw.quantity('1.5 kcal / mole', parser='pint', form='pint')
1.5 kilocalorie/mole
puw.convert('kelvin**(-1)', parser='pint', to_form='pint')
1.0 1/kelvin

And the inverse translation can be performed:

q = puw.convert('2 newtons per square meter', parser='pint', to_form='openmm.unit')
puw.convert(q, to_form='string')
'2.0 N/(m**2)'
u = puw.convert('kelvin**(-1)', to_type='unit')
u
Unit({BaseUnit(base_dim=BaseDimension("temperature"), name="kelvin", symbol="K"): -1.0})
puw.convert(u, to_form='string')
'/kelvin'