在 python 2.x 中,您可以执行以下操作:
>>> print '%.2f' % 315.15321531321
315.15
但是,我无法让它适用于 python 3.x,我尝试了不同的东西,例如
>>> print ('%.2f') % 315.15321531321
%.2f
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for %: 'NoneType' and 'float'
>>> print ("my number %") % 315.15321531321
my number %
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for %: 'NoneType' and 'float'
然后,我阅读了 .format() 方法,但我也无法让它工作
>>> "my number {.2f}".format(315.15321531321)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'float' object has no attribute '2f'
>>> print ("my number {}").format(315.15321531321)
my number {}
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'format'
我会很高兴任何提示和建议!