使用 %.*g 的 Python 数字打印格式

标签 python string-formatting

我在网上找到了这个 python 示例,我想确切地了解数字格式的工作原理:

print "%.*g\t%.*g" % (xprecision, a, yprecision, b)

我可以通过实验看到,这会打印 a(精度为 xprecision)、制表符,然后是 b(精度为 yprecision)。所以,作为一个简单的例子,如果我运行

print "%.*g\t%.*g" % (5, 2.23523523, 3, 12.353262)

然后我得到

2.2352  12.4

我了解 %g 通常是如何工作的。我也了解 % 通常是如何工作的。在这个例子中让我感到困惑的是结构 %.*g* 在这里如何工作?我可以看到它以某种方式获取所需的精度值并将其代入打印表达式,但为什么会这样?为什么精度数字出现在 (xprecision, a...) 格式的数字之前?

有人可以分解并向我解释吗?

最佳答案

* 是一个尺寸占位符。它告诉格式化操作从右侧元组中获取 下一个 值并将其用作精度。

在您的示例中,第一个插槽的“下一个”值为 5,因此您可以将其读作 %.5g,用于格式化 2.23523523。第二个插槽使用 3 作为宽度,因此变为 %.3g 以格式化 12.353262

参见 String Formatting Operations documenation :

A conversion specifier contains two or more characters and has the following components, which must occur in this order:

(...)

  1. Minimum field width (optional). If specified as an '*' (asterisk), the actual width is read from the next element of the tuple in values, and the object to convert comes after the minimum field width and optional precision.

  2. Precision (optional), given as a '.' (dot) followed by the precision. If specified as '*' (an asterisk), the actual width is read from the next element of the tuple in values, and the value to convert comes after the precision.

因此最小宽度和精度都可以通过 * 进行更改,并且文档明确指出要转换的值在宽度和精度之后

关于使用 %.*g 的 Python 数字打印格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35369155/

相关文章:

python - Python中C类型Switch语句实现的困惑

python - python字典上使用的 'in'子句是否每次都调用keys()函数?

python - SQLAlchemy ondelete 和 onupdate 不更新数据库

Python 字符串格式 : When to use ! s 转换标志

python - 检查字符串是否符合某种格式

python - 如何在 numpy 数组中查找值簇

Python - 单击时将 turtle 移动到鼠标

regex - python : extract all placeholders from format string

java - Java 中的自动格式化 HTML 字符串

java - 如何在 Java 中格式化信用卡号