reformat_unit

justunits.reformat_unit(text: str, target_format: Optional[enum.IntFlag] = None, converter: Optional[Callable[[str], Any]] = None) str

Reformats a attribute/value-unit pair to a targeted format. ‘None’ or missing style definitions are replaced by _defaults.

Parameters
  • text – Text containing an attribute/value-unit pair.

  • target_format – The format the attribute/value-unit pair gets. ‘None’ or not defined styles are set to _defaults.

  • converter – A callable converting a string into the desired object. A failed conversion must raise a ValueError. Default is str.

Returns

str

Examples

>>> import justunits
>>> from justunits import reformat_unit, AttributeUnitSeparators, UnitStyle
>>> reformat_unit("1 apple")
'1 [apple]'
>>> hashed = AttributeUnitSeparators.HASH_SIGN
>>> reformat_unit("1 apple", hashed)
'1#apple'
>>> fine_slashed_in_style = (
...     AttributeUnitSeparators.WHITESPACE_IN | UnitStyle.FINE_SLASHED_SUPERSCRIPT
... )
>>> reformat_unit("energy#kg/(m*s^2)")
'energy [kg/(m⋅s²)]'

By default single whitespace or underline separated units are not taken into account, allowing the distingtion between any attribute and trailing unit.

>>> reformat_unit("without unit")
'without unit'

Using a more distinguishable seperator enables the reformatting of ‘lazy’ written unit compositions like newton meter being a unit for torque. This is intential as being a method to make clean representations of units.

>>> reformat_unit("torque in Nm")
'torque [N⋅m]'

Note

The detection of ‘lazy’ written units like ‘Nm’ is being tested as the default behaviour of just units within the alpha state. You may help by feedbacks onto the github project page https://github.com/david.scheliga/justunits/issues in which cases this leads to problems.

Be aware that this tries for breaking unknown units into known parts. Leading to this such a behavior.

>>> reformat_unit("with a unit in unit*pattern")
'with a unit [u⋅nit⋅pattern]'
>>> justunits.from_string("unit")
(AUnit(u 'unified atomic mass unit' ), UnknownUnit('nit'))
>>> justunits.register_unit(justunits.create_unit("unit", "dummy", "n.a."))
>>> reformat_unit("with a unit in unit*pattern")
'with a unit [unit⋅pattern]'