格式():ValueError:整数格式说明符中不允许使用精度

新手上路,请多包涵

我是 python 新手。我刚刚熟悉格式方法。

从我正在阅读的一本书中学习python

 What Python does in the format method is that it substitutes each argument
value into the place of the specification. There can be more detailed specifications
such as:
decimal (.) precision of 3 for float '0.333'
>>> '{0:.3}'.format(1/3)
fill with underscores (_) with the text centered
(^) to 11 width '___hello___'
>>> '{0:_^11}'.format('hello')
keyword-based 'Swaroop wrote A Byte of Python'
>>> '{name} wrote {book}'.format(name='Swaroop', book='A Byte of Python')

如果我尝试在 python 解释器中

print('{0:.3}'.format(1/3))

它给出了错误

 File "", line 24, in
ValueError: Precision not allowed in integer format specifier

原文由 liv2hak 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.3k
2 个回答

要打印浮点数,您必须至少有一个输入为浮点数,如下所示

print('{0:.3}'.format(1.0/3))

如果除法运算符的两个输入都是整数,则返回的结果也将是 int,小数部分被截断。

输出

0.333

您可以使用 float 函数将数据转换为浮点数,如下所示

data = 1
print('{0:.3}'.format(float(data) / 3))

原文由 thefourtheye 发布,翻译遵循 CC BY-SA 3.0 许可协议

最好添加 f

 In [9]: print('{0:.3f}'.format(1/3))
0.000

通过这种方式,您可能会注意到 1/3 给出了一个 整数,然后将其更正为 1./31/3.

原文由 zhangxaochen 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题