In python 2.x you were allowed to do something like this:
>>> print '%.2f' % 315.15321531321
315.15
However, i cannot get it to work for python 3.x, I tried different things, such as
>>> 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'
Then, I read about the .format() method, but I cannot get it to work either
>>> "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'
I would be happy about any tips and suggestions!
Try sending the entire string with formatting to print.
print ('%.2f' % 6.42340)
Works with Python 3.2
In addition, the format works by providing an index to the provided agruments
print( "hello{0:.3f}".format( 3.43234 ))
Notice the '0' in front of the format flags.
The problem with your code is that in Python 3 print is no longer a keyword, it's a function, so this happens:
>>> print ('%.2f') % 315.15321531321
%.2f
Traceback.... #
Because it prints the string and later evaluates the "% 315.15321531321" part and of course fails, the same occurs with the other examples.
This is ok:
print(('%.2f') % 315.15321531321)
来源:https://stackoverflow.com/questions/14815417/cannot-figure-out-how-string-substitution-works-in-python-3-x