Cannot Figure out how String Substitution works in

2020-04-10 01:10发布

问题:

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 7 years ago.

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!

回答1:

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.



回答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)