Python 格式():值错误:整数格式说明符中不允许使用精度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21200098/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 22:17:15  来源:igfitidea点击:

format () : ValueError: Precision not allowed in integer format specifier

pythonstringpython-3.x

提问by liv2hak

I am a python newbie.I am just getting acquainted with format method.

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

From a book that I am reading to learn 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')

In the python interpreter if I try

如果我尝试在 python 解释器中

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

It gives the error

它给出了错误

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

采纳答案by thefourtheye

To print the floating point numbers, you have to have atleast one of the inputs as floats, like this

要打印浮点数,您必须至少有一个输入作为浮点数,就像这样

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

If both the inputs are integers to the division operator, the returned result will also be in int, with the decimal part truncated.

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

Output

输出

0.333

You can convert the data to float with floatfunction, like this

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

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

回答by zhangxaochen

It's better to add f:

最好添加f

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

in this way you could notice that 1/3gives an integerand then correct that to 1./3or 1/3..

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

回答by Hyman

It is worth noting that this error will only happen in python 2. In python 3, division always returns a float.

值得注意的是,这个错误只会在python 2中发生。在python 3中,除法总是返回一个浮点数。

You can replicate this with the from __future__ import divisionstatement in python 2.

您可以使用from __future__ import divisionpython 2 中的语句复制它。

~$ python
Python 2.7.6 
>>> '{0:.3}'.format(1/3)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: Precision not allowed in integer format specifier
>>> from __future__ import division
>>> '{0:.3}'.format(1/3)
'0.333'