从Python3编写“表”

时间:2010-11-09 01:12:55

标签: python python-3.x

如何在文件的一行中写入多个字符串和多个变量输出以进行输出? 我知道write()只接受一个参数,但理想情况下这就是我想要实现的目标:

write('Temperature is', X , 'and pressure is', Y)

结果将是一张桌子。

你能帮忙吗?

2 个答案:

答案 0 :(得分:2)

write('Temperature is {0} and pressure is {1})'.format(X,Y))

如果您想要更多地控制输出,可以执行以下操作:

X = 12.3
Y = 1.23
write('Temperature is {0:.1f} and pressure is {1:.2f})'.format(X,Y))
# writes 'Temperature is 12.3 and pressure is 1.2'

此处的文档和示例:http://docs.python.org/py3k/library/string.html

答案 1 :(得分:2)

f = open("somefile.txt", "w")
print('Temperature is', X , 'and pressure is', Y, file=f)