我是一个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 发布于 2014-01-18 12:47:20
要打印浮点数,必须至少有一个输入作为浮点数,如下所示
print('{0:.3}'.format(1.0/3))如果两个输入都是除法运算符的整数,则返回的结果也将是int格式,小数部分将被截断。
输出
0.333您可以使用float函数将数据转换为浮点型,如下所示
data = 1
print('{0:.3}'.format(float(data) / 3))发布于 2014-01-18 12:53:26
最好是添加f
In [9]: print('{0:.3f}'.format(1/3))
0.000通过这种方式,您可以注意到1/3提供了一个整数,然后将其更正为1./3或1/3.。
发布于 2015-08-01 02:40:48
值得注意的是,这个错误只会在python 2中发生。在python 3中,this总是返回一个浮点数。
您可以使用Python2中的from __future__ 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'https://stackoverflow.com/questions/21200098
复制相似问题