Skip to content
Advertisement

Format Pint unit as short-form symbol

Say I have an arbitrary Pint quantity q. Is there a way to display its units in symbol short form, instead of as a full-length word?

In other words, how would I code unit_symbol() such that it returns “m”, not “meter”; “kg” not “kilogram”; etc.? Is there a way to retrieve the short-form unit symbol that is synonym with the quantity’s current unit?

import pint 
ureg = pint.UnitRegistry()
Q_ = ureg.Quantity

def unit_symbol(q: pint.Quantity) -> str:
    # Intended to return "m", not "meter"
    # "kg" not "kilogram"
    # etc.
    # ???
    return q.units  # returns long-form unit, "meter", "kilogram" etc. :-(
    
q = Q_(42, ureg.m)
print(unit_symbol(q))  # "meter"... whereas I would like "m"

The above obviously fails to achieve this; it returns the long-form unit.

Advertisement

Answer

You can use '~' as a spec for the unit formatting:

q = Q_(42, "m") / Q_(1, "second")

print(format(q, '~'))  # 42.0 m / s
print(format(q.u, '~'))  # m / s

This feature is apparently undocumented, but can be inferred from the source code for Unit.__format__ (search for "~" on that page to quickly navigate to the relevant piece of code).

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement