将表格保存为文本
我现在有的内容:
oname = open("1231.txt","w")
def cC_():
d_=" fahrenheit celsius"
print(d_)
for i in range(-300,213,1):
c_=(i-32)*(5/9)
a_=str(i)+'°F'
b_=str(round(c_,3))+'°C'
print("%10s" % (a_), ' ',"%10s" % (b_))
oname.write(cC_())
oname.close()
我的问题是:我无法得到一个像函数打印出来的文本那样的表格。
华氏温度 摄氏温度
-300°F -184.444°C
-299°F -183.889°C
-298°F -183.333°C
-297°F -182.778°C
-296°F -182.222°C
-295°F -181.667°C
-294°F -181.111°C
-293°F -180.556°C
-292°F -180.0°C
.........
4 个回答
0
你在写函数的时候,关注的是函数的返回值,而不是函数里打印出来的字符串。
你应该把打印的部分改成使用 oname.write。
with open("1231.txt","w") as oname:
oname.write(" fahrenheit celsius\n")
for i in range(-300,213,1):
c_=(i-32)*(5/9)
a_=str(i)+'°F'
b_=str(round(c_,3))+'°C'
oname.write("".join(("%10s" % (a_), ' ',"%10s\n" % (b_))))
补充:
有一种更好的方法,可以使用 .format
来代替字符串转换(你也可以用以前的 % 符号来做这件事)。
with open("1231.txt","w") as oname:
oname.write(" fahrenheit celsius\n")
for i in range(-300,213,1):
c=(i-32)*(5/9)
oname.write("{0:<10.3f}°F {1:<10.3f}°C \n".format(i, c))
0
Ignacio的回答适用于Python 3,对于Python 2,你应该这样做...
def cC_(fout=sys.stdout):
...
print >> fout, ...
with open(..., 'w') as oname:
cC_(oname)
2
def cC_(fout=sys.stdout):
...
print(..., file=fout)
...
with open(..., 'w') as oname:
cC_(oname)
当然可以!请把你想要翻译的内容发给我,我会帮你用简单易懂的语言解释清楚。