2015-09-18 16 views
1

我是新來的python,最近我已經遷移到Python 3和 我試圖去習慣format()函數。如何在Python格式函數中應用「%.02f」?

我試圖做的是print()溫度我浮點創建 ,就像這樣:

temperature = [23, 24, 25, 26, 27] 
print("Today's temperature is %.02f" % (temperature[0])) 

而不是使用%.02f的,我想知道如何 可能被寫入在format()函數中代替%而不是 的百分比。

+3

' '... {:. 02F}'' - RTFM! – jonrsharpe

+0

謝謝!這工作! – PrimeHack

回答

5

你將不得不使用{:.02f}

>>> temperature = [23, 24, 25, 26, 27] 
>>> print("Today's temperature is %.02f" % (temperature[0])) 
Today's temperature is 23.00 
>>> print("Today's temperature is {:.02f}".format(temperature[0])) 
Today's temperature is 23.00 

更多信息可以在documentation找到。但是也看到Format Examples

'%03.2f'可以轉化爲'{:03.2f}'

+0

令人驚歎!謝謝!這應該做到這一點! – PrimeHack

相關問題