2013-05-13 69 views
0

我剛開始學習python,目前正在編寫一個腳本,將攝氏溫度轉化爲華氏溫度,反之亦然。我已經完成了主要部分,但現在我希望能夠讓用戶設置輸出中顯示的小數位數......第一個函數包含我失敗的嘗試,第二個函數設置爲2位小數。用戶設置的函數中的可變小數點限制?

def convert_f_to_c(t,xx): 
c = (t - 32) * (5.0/9) 
print "%.%f" % (c, xx) 

def convert_c_to_f(t): 
    f = 1.8 * t + 32 
    print "%.2f" % f  


print "Number of decimal places?" 
dec = raw_input(">") 

print "(c) Celsius >>> Ferenheit\n(f) Ferenheit >>> Celcius" 
option = raw_input(">") 

if option == 'c': 
    cel = int(raw_input("Temperature in Celcius?")) 
    convert_c_to_f(cel) 

else: 
    fer = int(raw_input("Temperature in Ferenheit?")) 
    convert_f_to_c(fer,dec) 

回答

5
num_dec = int(raw_input("Num Decimal Places?") 
print "%0.*f"%(num_dec,3.145678923678) 

在%格式字符串,你可以使用一個*此功能

AFAIK存在'{}'.Format方法沒有equivelent方法

>>> import math 
>>> print "%0.*f"%(3,math.pi) 
3.142 
>>> print "%0.*f"%(13,math.pi) 
3.1415926535898 
>>> 
+0

「%0. * f」%(13,math.pi)的操作對我來說有點令人困惑,因爲*是在%之前定義的......任何原因爲什麼?或者只是約定。 在我的背景下,成爲 '打印 「0%* F」 %(XX,C)' 和它的作品! 謝謝 – AllTheTime1111 2013-05-13 23:11:35

+0

@ AllTheTime1111:閱讀[docs](http://docs.python.org/2/library/stdtypes.html#string-formatting-operations)。我同意這不是最簡單的理解,但它在那裏。特別注意關於精度的部分(編號列表中的第5項解釋轉換說明符)。 – 2013-05-13 23:16:34

+2

''{0:。{1} f}'。format(math.pi,3)'是新方法 – Eric 2013-05-13 23:18:37

1

這工作:

>>> fp=12.3456789 
>>> for prec in (2,3,4,5,6): 
... print '{:.{}f}'.format(fp,prec) 
... 
12.35 
12.346 
12.3457 
12.34568 
12.345679 

這個例子也一樣:

>>> w=10 
>>> for prec in (2,3,4,5,6): 
... print '{:{}.{}f}'.format(fp,w,prec) 
... 
    12.35 
    12.346 
    12.3457 
    12.34568 
12.345679 

甚至:

>>> align='^' 
>>> for prec in (1,2,3,4,5,6,7,8,9): 
...    print '{:{}{}.{}f}'.format(fp,align,15,prec) 
...  
     12.3       
     12.35      
    12.346      
    12.3457     
   12.34568     
   12.345679    
  12.3456789    
  12.34567890   
 12.345678900 

它會自動字段選擇毛髮過多之前,您可以使用手動也和周圍交換領域:

>>> for prec in (2,3,4,5,6): 
... print '{2:{0}.{1}f}'.format(w,prec,fp) 
... 
    12.35 
    12.346 
    12.3457 
    12.34568 
12.345679 

最好的文檔是在PEP 3101