我是 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 许可协议
要打印浮点数,您必须至少有一个输入为浮点数,如下所示
如果除法运算符的两个输入都是整数,则返回的结果也将是 int,小数部分被截断。
输出
您可以使用
float
函数将数据转换为浮点数,如下所示