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?

JavaScript

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

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