宽度和精度使用 *
我正在从一本书中学习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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为您的意思是这样的:
4
是一个通配符值,用于代替星号*
。展开后它相当于:I think you meant something like this:
4
is a wild card value that is used in place of asterisk*
. When expanded it would be equivalent to:您发布的行中有两个语法错误。 1.3.0 不是有效数字,并且该字符串不是闭合的。
这是所述字符串格式的有效版本。
和输出:
我在 官方文档中找不到有关 %.*f 的文档。然而,它似乎将 4 解析为您想要执行下一个参数的小数位数。
例如:
returns
和
returns
这似乎是一种提供可变长度精度的方法,因此您可以允许用户指定它。
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.
and outputs:
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:
returns
and
returns
It seems to be a way to offer variable length precision, so you could allow your users to specify it.