首页 > 解决方案 > Need to add formatting to a string reduced to x significant figures

问题描述

I need to format a text file, but some values (required to 6SF) are out of line with the rest of the document. See below:

import numpy as np     
A1=np.linspace(1., 10**15., 1000)
f = open('document.txt', 'w')
f.write('Document of values' + "\n")
f.write('Column 1' + "\t" + "\t" + 'Column 2' + "\t" + 'Column 3' + "\n")
for i in range(len(A1)):
    f.write(str("%.6g" % A1[i]) + "\t " + "\t" + str("%.6g" % A1[i]) + "\t" + "\t" + "\t" + str("%.6g" % A1[i]) +"\n")
f.close()

Currently I am attempting something along the lines of this:

import numpy as np  
A1=np.linspace(1., 10**15., 1000)
A2=str(A1)
A3=str(A1)
for i in range(len(A2)):
    if 'e' in A2[i]:
        A3[i]=("%.6g" % A2[i])
    else:
        A3[i]=(("%.6g" % A2[i]) + "\t")

f = open('document.txt', 'w')
f.write('Document of values' + "\n")
f.write('Column 1' + "\t" + 'Column 2' + "\t" + 'Column 3' + "\n")
for i in range(len(A1)):
    f.write(str(A3[i]) + "\t" + "\t" + str("%.6g" % A1[i]) + "\t" + "\t" + "\t" + str("%.6g" % A1[i]) +"\n")
f.close()

In order to add an additional /t to the values in column 1 that don't have an e+xx value in them. The output must be in a .txt file. How can I achieve this?

标签: pythonarraysstringformatting

解决方案


您确定需要用制表符分隔数字吗?

选项卡在不同的文本编辑器中看起来不同(有时选项卡 = 4 个空格,有时是 2 个,有时是 8 个)

使用简单的空间,您可以轻松实现您想要的。

只需将您的数字用空格填充到所需的长度。

您已经对部分字符串进行了格式化,您只需要使用 ljust 或 rjust 字符串函数:

("%.6g" % x).rjust(8)- 对于 x = 0 或 x = 999999.999999,将始终为您提供 8 个字符的字符串

因此,将这些结构组合到您需要构建的列中,您会没事的!


推荐阅读