宽度和精度使用 *

发布于 2024-08-12 00:52:08 字数 181 浏览 2 评论 0原文

我正在从一本书中学习Python,并遇到了这个例子:

>>> '%f, %.2f, %.*f % (1/3.0, 1/3.0, 4, 1/3.0)
# Result: '0.333333, 0.33, 0.3333'

不太明白这里发生了什么,尤其是中间的“4”。

I'm learning Python from a book and came across this example:

>>> '%f, %.2f, %.*f % (1/3.0, 1/3.0, 4, 1/3.0)
# Result: '0.333333, 0.33, 0.3333'

Don't quite understand what's happening here, especially the '4' in between.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

梅倚清风 2024-08-19 00:52:08

我认为您的意思是这样的:

>>> '%f, %2.f, %.*f' % (1/3.0, 1.3, 4, 1/3.0)
'0.333333,  1, 0.3333'

4 是一个通配符值,用于代替星号 *。展开后它相当于:

>>> '%f, %2.f, %.4f' % (1/3.0, 1.3, 1/3.0)

I think you meant something like this:

>>> '%f, %2.f, %.*f' % (1/3.0, 1.3, 4, 1/3.0)
'0.333333,  1, 0.3333'

4 is a wild card value that is used in place of asterisk *. When expanded it would be equivalent to:

>>> '%f, %2.f, %.4f' % (1/3.0, 1.3, 1/3.0)
知你几分 2024-08-19 00:52:08

您发布的行中有两个语法错误。 1.3.0 不是有效数字,并且该字符串不是闭合的。

这是所述字符串格式的有效版本。

'%f, %2.f, %.*f' % (1/3.0, 1/3.0, 4, 1/3.0)

和输出:

'0.333333, 0.33, 0.3333'

我在 官方文档中找不到有关 %.*f 的文档。然而,它似乎将 4 解析为您想要执行下一个参数的小数位数。

例如:

'%.*f' % (5, 1/3.0)

returns

'0.33333'

'%.*f' % (6, 1/3.0)

returns

'0.333333'

这似乎是一种提供可变长度精度的方法,因此您可以允许用户指定它。

There are two syntax errors in the line you posted. 1.3.0 isn't a valid number, and the string isn't closed.

This is a valid version of said string format.

'%f, %2.f, %.*f' % (1/3.0, 1/3.0, 4, 1/3.0)

and outputs:

'0.333333, 0.33, 0.3333'

I couldn't find documentation on %.*f in the official docs. However, it appears that it's parsing the 4 to be how many decimal places you want to do the next argument at.

For example:

'%.*f' % (5, 1/3.0)

returns

'0.33333'

and

'%.*f' % (6, 1/3.0)

returns

'0.333333'

It seems to be a way to offer variable length precision, so you could allow your users to specify it.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文