简体   繁体   中英

Python Pint: set short representation of units as default

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?

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 (eg mm instead of millimeter ).

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM