【问题标题】:Python Pint: set short representation of units as defaultPython Pint:将单位的短表示设置为默认值
【发布时间】:2021-12-04 18:39:00
【问题描述】:

品脱单位默认以其全名表示:

>>> 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²

从文档和 this answer 中可以看出,单位可以用它们的缩写形式表示,这是它们在现实世界中通常表示的方式:

>>> print(format(q,'~'))
3.456 m ** 2
>>> print('The pretty representation is {:~P}'.format(q))
The pretty representation is 3.456 m²

但是,我想将短表示设置为默认值,可以吗?

【问题讨论】:

    标签: python representation pint


    【解决方案1】:

    我不知道它是错误的、弱的还是非pythonic的,但它似乎有效,我正在使用它,直到出现更好的解决方案:

    import pint
    pint.quantity.Quantity.__str__ = lambda self: format(self,'~')
    

    在脚本开头添加这样的行后,所有单位的字符串表示形式都以短格式返回(例如 mm 而不是 millimeter)。

    【讨论】:

      【解决方案2】:

      我在tutorial字符串格式这部分的底部找到了这个。这是一个最小的工作示例:

      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}')
      

      这个输出:The acceleration is 1.3 m / s ** 2

      这些也是短单元的有效选项:~L (LaTeX)、~H (HTML) 和 ~P (Pretty print)。

      【讨论】:

        猜你喜欢
        • 2011-09-17
        • 1970-01-01
        • 2011-04-06
        • 2010-10-10
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多