Cannot Figure out how String Substitution works in Python 3.x [closed]

坚强是说给别人听的谎言 提交于 2019-12-01 18:31:01

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)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!