Python 用户设置的函数中的可变小数位数限制?
我刚开始学习python,目前正在编写一个脚本,可以将摄氏温度转换为华氏温度,反之亦然。我已经完成了主要部分,但现在我希望能够让用户设置输出中显示的小数位数。。。第一个函数包含我失败的尝试,第二个函数设置为小数点后2位Python 用户设置的函数中的可变小数位数限制?,python,Python,我刚开始学习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
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)
在%格式字符串中,您可以将*
用于此功能
afaik在“{}”格式中没有等价的方法
>>> import math
>>> print "%0.*f"%(3,math.pi)
3.142
>>> print "%0.*f"%(13,math.pi)
3.1415926535898
>>>
在%格式字符串中,您可以将*
用于此功能
afaik在“{}”格式中没有等价的方法
>>> import math
>>> print "%0.*f"%(3,math.pi)
3.142
>>> print "%0.*f"%(13,math.pi)
3.1415926535898
>>>
这项工作:
>>> 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中这很有效:
>>> 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中对“%0.*f”%(13,math.pi)的操作让我有点困惑,因为*是在%之前定义的。。。有什么原因吗?或者只是惯例。在我的上下文中,它变成了打印“%0.*f”%(xx,c)
,并且可以工作!thanks@AllTheTime1111:阅读。我同意这不是最简单的理解,但它就在那里。请特别注意有关精度的部分(编号列表中的第5项解释了转换说明符)。啊,感谢eric,这很有意义。。。但是为了公平起见,python.org已经收回了关于%被贬值和消失的部分“%0.*f”%(13,math.pi)的操作对我来说有点混乱,因为*是在%之前定义的。。。有什么原因吗?或者只是惯例。在我的上下文中,它变成了打印“%0.*f”%(xx,c)
,并且可以工作!thanks@AllTheTime1111:阅读。我同意这不是最简单的理解,但它就在那里。请特别注意有关精度的部分(编号列表中的第5项解释了转换说明符)。啊,感谢eric,这很有意义。。。但为了公平起见,python.org已经收回了关于%被贬值和消失的说法