我是一个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
要打印浮点数,必须至少有一个输入为float,如下所示
如果两个输入都是除法运算符的整数,则返回的结果也将是int,小数部分将被截断。
输出
可以使用
float
函数将数据转换为浮点,如下所示值得注意的是,这个错误只会在python 2中发生。在python 3中,division总是返回一个float。
您可以使用python 2中的
from __future__ import division
语句来复制此语句。最好加上
f
:通过这种方式,您可以注意到
1/3
给出了一个整数,然后将其更正为1./3
或1/3.
。相关问题 更多 >
编程相关推荐