【问题标题】:Python - formating numbers of an ascii table [duplicate]Python - 格式化ascii表的数字[重复]
【发布时间】:2023-03-10 16:56:01
【问题描述】:

我想知道为什么我的代码不起作用。我想在小数点后仅用 2 个数字舍入两列数据。我现在正在关注以下代码:

from __future__ import print_function

with open('input.dat', 'r') as f, open('output.txt', 'w') as outfile:
    for line in f:
        try:
            line = line.strip()
            columns = line.split()
            vx = float(columns[0])
            vy = float(columns[1])
            print("{:.2f\t}".format(vx),"{:.2f}".format(vy), file=outfile)
        except ValueError:
            print(line, file=outfile)

输入数据如下

XY
HH
M&M
TS
1.83746 2.12131
1.12121 1.89942
1.32435 1.99443
1.65392 2.00001
1.48732 2.21773
...
...

输出应如下所示:

XY
HH
M&M
TS
1.84    2.12
1.12    1.90
1.32    1.99
1.65    2.00
1.49    2.22
...
...

【问题讨论】:

    标签: python python-3.x formatting numbers text-files


    【解决方案1】:

    我认为这条线是错误的

    print("{:.2f\t}".format(vx),"{:.2f}".format(vy), file=outfile)
    

    标签应该在{}之外,我会像这样重写它

    print("{:.2f}\t{:.2f}".format(vx, vy), file=outfile)
    

    【讨论】:

      猜你喜欢
      • 2015-03-03
      • 1970-01-01
      • 1970-01-01
      • 2023-01-28
      • 2015-01-07
      • 2018-12-05
      • 2016-12-06
      • 2014-09-30
      相关资源
      最近更新 更多