无法弄清楚字符串替换在 Python 3.x 中是如何工作的

问题描述

在 python 2.x 中,你可以这样做:

In python 2.x you were allowed to do something like this:

>>> print '%.2f' % 315.15321531321
315.15

但是,我无法让它在 python 3.x 上工作,我尝试了不同的方法,例如

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'

然后,我阅读了 .format() 方法,但我也无法让它工作

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)

适用于 Python 3.2

Works with Python 3.2

此外,该格式通过为所提供的 agruments 提供索引来工作

In addition, the format works by providing an index to the provided agruments

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

注意格式标志前面的0".

Notice the '0' in front of the format flags.

相关文章