0

从网站https://pint.readthedocs.io/en/stable/tutorial.html#string-formatting 您可以使用漂亮的表示{:~P}'.format(accel)来获得简短的单位表示。我可以定义自己的短格式吗?我不想使用 Pint 的默认格式。我如何自己定义它?谢谢!

如果您想使用缩写的单位名称,请在规范前面加上 ~:

>>> 'The str is {:~}'.format(accel)
'The str is 1.3 m / s ** 2'
>>> 'The pretty representation is {:~P}'.format(accel)
'The pretty representation is 1.3 m/s²'

LaTeX (L) 和 HTML (H) 规范也是如此。

注意 缩写单位取自单位注册表,当使用前缀“~”时,将返回等价链中的第 3 项(即 1 = 2 = 3)。链中的第一项是单位的规范名称。

格式化规范(即“L”、“H”、“P”)可以与 Python 字符串格式化语法一起用于自定义浮点表示。例如,科学记数法:

>>> 'Scientific notation: {:.3e~L}'.format(accel)
'Scientific notation: 1.300\\times 10^{0}\\ \\frac{\\mathrm{m}}{\\mathrm{s}^{2}}'
4

0 回答 0