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?
JavaScript
x
14
14
1
import pint
2
ureg = pint.UnitRegistry()
3
Q_ = ureg.Quantity
4
5
def unit_symbol(q: pint.Quantity) -> str:
6
# Intended to return "m", not "meter"
7
# "kg" not "kilogram"
8
# etc.
9
# ???
10
return q.units # returns long-form unit, "meter", "kilogram" etc. :-(
11
12
q = Q_(42, ureg.m)
13
print(unit_symbol(q)) # "meter"... whereas I would like "m"
14
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:
JavaScript
1
5
1
q = Q_(42, "m") / Q_(1, "second")
2
3
print(format(q, '~')) # 42.0 m / s
4
print(format(q.u, '~')) # m / s
5
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).