我是Python的初學者,我跑過下面的例子,但我開始修改它,因爲好奇心得到了我最好的。實際上有兩個相關的問題,理解它們可能會幫助我理解.format()實際做了什麼,以及限制是什麼。我已經研究過的文件,但我的具體的例子是從未提及。Python中的.format()功能
我開始使用此代碼擺弄:
print 'The diameter of {planet} is {measure} kilometers'.format(planet="Earth", measure=12742.34)
其產生的輸出:
The diameter of Earth is 12742.34 kilometers
但後來我開始問自己......「這種.format()的東西有多靈活?」
問題1
我如何避免蟒蛇做當我選擇{}的措施是一個數學輸出四捨五入?
print 'The diameter of {planet} is {measure}'.format(planet="Earth", measure=10/3)
The diameter of Earth is 3 kilometers
問題2
如何強制措施{}的浮動? 僞(我知道這是行不通的,但這裏將作爲參考)
print 'The diameter of {planet} is {0:.2f}{measure}'.format(planet="Earth", measure=10/3)
'from __future__ import division' – Natecat
''得到相同的行爲。這不會回答您的問題,但是理解字符串格式是一個很好的資源:https://pyformat.info/ – elethan