4

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!

Lev Levitsky
  • 63,701
  • 20
  • 147
  • 175
  • 1
    "{:.2f}" works for format, you need the : before specifying the formats like you are used to as a separator from the positional or key based arg selection – cmd Feb 11 '13 at 15:51

2 Answers2

4

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.

zanegray
  • 768
  • 7
  • 13
  • 1
    Oh, could have thought of that! Thank you so much! Btw. you need to add a period within the number 343234 to make it work. –  Feb 11 '13 at 16:04
2

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)
MGP
  • 2,981
  • 35
  • 34