使用format()对齐并打印浮动列表 [英] Round, align and print list of floats with format()
本文介绍了使用format()对齐并打印浮动列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要写几个浮动文件,我使用 format()
方法。我想要的是将浮点数四舍五入到给定的小数位数和同时写入它们。
I need to write several floats to file for which I am using the format()
method. What I want is to round the floats to a given number of decimal places and write them aligned at the same time.
这是一个MWE:
a = 546.35642
b = 6785.35416
c = 12.5235
d = 13.643241
line = [str('{:.2f}'.format(a)),
str('{:.4f}'.format(b)),
str('{:.5f}'.format(c)),
str('{:.3f}'.format(d))]
with open('format_test.dat', "a") as f_out:
f_out.write('''{:>10} {:>15} {:>16} {:>15}'''.format(*line))
f_out.write('\n')
对我来说似乎非常复杂。有没有更好的方式来使用 format()
?
This gets the job done but it seems awfully convoluted to me. Is there a better way to do this using format()
?
推荐答案
你可以用对齐的格式添加。#f
。
You can just add the .#f
in the format with the alignment.
with open('format_test.dat', "a") as f_out:
f_out.write('''{:>10.2f} {:>15.4f} {:>16.5f} {:>15.3f}'''.format(a, b, c, d))
f_out.write('\n')
这篇关于使用format()对齐并打印浮动列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文