0

I just started learning python and am currently writing a script that converts Celsius to Fahrenheit and vise versa. I have the main part done but now I want to be able to let the user set the number of decimals displayed in the output... The first function contains my failed attempt and the second is set at 2 decimal places.

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)
4

2 回答 2

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

在 % 格式的字符串中,您可以将 a*用于此功能

afaik方法中没有等效的'{}'.Format方法

>>> import math
>>> print "%0.*f"%(3,math.pi)
3.142
>>> print "%0.*f"%(13,math.pi)
3.1415926535898
>>>
于 2013-05-13T23:03:03.137 回答
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中

于 2013-05-13T23:35:18.470 回答