Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/341.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python format():ValueError:整数格式说明符中不允许精度_Python_String_Python 3.x - Fatal编程技术网

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

Python format():ValueError:整数格式说明符中不允许精度,python,string,python-3.x,Python,String,Python 3.x,我是一个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 '

我是一个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 

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

print('{0:.3}'.format(1.0/3))
data = 1
print('{0:.3}'.format(float(data) / 3))
如果两个输入都是除法运算符的整数,则返回的结果也将是int,小数部分将被截断

输出

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

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

最好添加
f

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

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

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

在Python2中,您可以使用
from\uuuuuu future\uuuuuu import division
语句来复制这一点

~$ 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'
~$python
Python 2.7.6
>>>“{0:.3}”。格式(1/3)
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
ValueError:整数格式说明符中不允许精度
>>>来自未来进口部
>>>“{0:.3}”。格式(1/3)
'0.333'

{0:.3}是什么意思?格式如何替代这些值?