Unable to determine how String Substitution works in Python 3.x

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, for example

 >>> 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 can't 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 glad to any tips and suggestions!

+4
source share
2 answers

Try sending the entire formatted string for printing. A.

 print ('%.2f' % 6.42340) 

Works with Python 3.2

In addition, the format works by pointing to the provided agents.

 print( "hello{0:.3f}".format( 3.43234 )) 

Note the "0" in front of the format flags.

+4
source

The problem with your code is that in Python 3, printing is no longer a keyword, it is a function, so this happens:

 >>> print ('%.2f') % 315.15321531321 %.2f Traceback.... # 

Since it prints a line and then evaluates the part "% 315.15321531321" and, of course, fails, this also happens with other examples.

This is normal:

 print(('%.2f') % 315.15321531321) 
+2
source

All Articles