2017-01-04 42 views
1

我是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) 
+0

'from __future__ import division' – Natecat

+0

''得到相同的行爲。這不會回答您的問題,但是理解字符串格式是一個很好的資源:https://pyformat.info/ – elethan

回答

0

你可以施放做measure = 10/ float(3)浮動。如果分子或分母是一個浮點數,那麼結果也是。

在Python 3.x中,單斜線(/)總是意味着真實(非截斷)分裂。 (//運算符用於截斷除法。)在Python 2.x(2.2及以上版本)中,您可以通過將from __future__ import division

1

這意味着你正在使用Python 2.x和你有很多的選擇,因爲默認的整數除法結果的整數

選項1:導入除法庫

from __future__ import division 

選項2:改變任何一個因素浮動或可替代地可以通過ading 0.0將其改爲3浮動(小數點),或者含多處Ÿ1.0

print 'The diameter of {planet} is {measure:.2f}'.format(planet="Earth", measure=10/3.0) 
+0

無論哪種方式,請注意'格式'不涉及;它會得到賦給'measure'的表達式的* result *,而不是表達式本身。 – chepner

+0

是的,度量的值在進行格式化時已經計算出來。 –

+0

我試過'print'{planet}的直徑是{0:.2f} {measure}'。格式(planet =「Earth」,measure = 10/3。0)「,但這給了我以下錯誤:IndexError:元組索引超出範圍 – treefiddy

-1

你也可以只做到:

print 'The diameter of {} is {}'.format("Earth",10/3) 
+0

10/3 = 3在python 2.這就是要點。 –