Reputation: 5780
Pint units are represented by default with their full name:
>>> import pint
>>> ureg = pint.UnitRegistry()
>>> q = ureg.Quantity('3.456 m^2')
>>> print(q)
3.456 meter ** 2
>>> print('The pretty representation is {:P}'.format(q))
The pretty representation is 3.456 meter²
From the docs and from this answer it comes out that units can be represented in their short form, which is the way they are commonly represented in the real world:
>>> print(format(q,'~'))
3.456 m ** 2
>>> print('The pretty representation is {:~P}'.format(q))
The pretty representation is 3.456 m²
However, I would like to set the short representation as default, is it possible?
Upvotes: 1
Views: 1112
Reputation: 92
I found this at the bottom of this section String formatting in the tutorial. This is a minimal working example:
import pint
ureg = pint.UnitRegistry()
ureg.default_format = '~' # Add this if you want to use abbreviated unit names.
accel = 1.3 * ureg['meter/second**2']
print(f'The acceleration is {accel}')
This outputs: The acceleration is 1.3 m / s ** 2
These are also valid options for short units: ~L
(LaTeX), ~H
(HTML) and ~P
(Pretty print).
Upvotes: 2
Reputation: 5780
I don't know if it's wrong, weak or non-pythonic, but it seems to work and I'm using this, until better solution arise:
import pint
pint.quantity.Quantity.__str__ = lambda self: format(self,'~')
After you add such line at the beginning of your script all the string representations of units are returned in short form (e.g. mm
instead of millimeter
).
Upvotes: 0