1

我想制作一个在非常基本的级别上进行复制的程序,并显示所有股票价格及其拥有的数量,整齐地保持列在同一行,使其看起来整洁。我试过做这个代码:

print '{:1s} {:1s} {:1s} {:4.2f} {:1s} {:10d} {:1s}'.format('|','NAME','|',53.63,'|', 10000000, '|')
print '{:1s} {:1s} {:1s} {:4.2f} {:1s} {:10d} {:1s}'.format('|','NAME','|',4837.34,'|', 1000000000, '|')

但是这样显示它们:

| NAME | 53.63 |   10000000 |
| NAME | 4837.34 | 1000000000 |

我希望它像这样显示

| NAME |  53.63  | 10000000   |
| NAME | 4837.34 | 1000000000 |

或以类似的方式。我希望它们两边的线条对齐,这样看起来更整洁

有没有办法让我能够做到这一点?

提前致谢

4

3 回答 3

2

像这样的东西:

print '| {:^4} | {:^7.2f} | {:<10} |'.format('NAME', 53.63, 10000000)
print '| {:^4} | {:^7.2f} | {:<10} |'.format('NAME',4837.34,1000000000)

输出:

| NAME |  53.63  | 10000000   |
| NAME | 4837.34 | 1000000000 |

您还可以从以下位置传递字段宽度format

print '| {:^{}} | {:^{}.2f} | {:<{}} |'.format('NAME', 4, 53.63, 7, 10000000, 10)
print '| {:^{}} | {:^{}.2f} | {:<{}} |'.format('NAME', 4, 4837.34, 7, 1000000000, 10)

输出:

| NAME |  53.63  | 10000000   |
| NAME | 4837.34 | 1000000000 |
于 2013-11-05T07:31:03.053 回答
1

使用文档中描述的Format Specification Mini-Language,您可以对每个字段使用可选的宽度说明符(以及其他控制数值对齐和精度的说明符)。

fmt = '| {:^8s} | {:>10,.2f} | {:>14,d} |'
print fmt.format('NAME', 53.63, 10000000)
print fmt.format('NAME', 4837.34, 1000000000)

宽度值也可以与字段数据混合:

fmt = '| {:^{}s} | {:>{},.2f} | {:>{},d} |'
print fmt.format('NAME', 8, 53.63, 10, 10000000, 14)
print fmt.format('NAME', 8, 4837.34, 10, 1000000000, 14)

或者可以在单独的步骤中提供每个值,以将两种类型的值分开:

fmt = '| {{:^{}s}} | {{:>{},.2f}} | {{:>{},d}} |'.format(8, 10, 14) # widths only
print fmt.format('NAME', 53.63, 10000000) # data only
print fmt.format('NAME', 4837.34, 1000000000)

不管怎样,这将是输出:

|   NAME   |      53.63 |     10,000,000 |
|   NAME   |   4,837.34 |  1,000,000,000 |

显然你需要提前知道每列数据的最大宽度。如果不知道,那么您可能必须检查每列中的所有值以找到最大的值,以确定要使用的正确字段宽度说明符值——假设所有数据在输出之前都可用。

于 2013-11-05T08:26:06.150 回答
0

假设您在某个制表符分隔的文件中有数据,首先,这应该适合您:

def tabularize(infilepath, outfilepath, delim='\t', largeFile=False):
    """ Return nothing
        Write into the file in outfilepath, the contents of infilepath, expressed in tabular form.
        The tabular form is similar to the way in which SQL tables are displayed.
        If largeFile is set to True, then no caching of lines occurs. However, two passes of the infile are required"""

    if largeFile:
        widths = getWidths(infilepath, delim)
    else:
        with open(infilepath) as infile:
            lines = [line.strip().split(delim) for line in infile.readlines() if line.strip()]
        widths = [max([len(row) for row in rows])+2 for rows in izip_longest(*lines, fillvalue="")]

        with open(outfilepath, 'w') as outfile:
            outfile.write("+")
            for width in widths:
                outfile.write('-'*width + "+")
            outfile.write('\n')
            for line in lines:
                outfile.write("|")
                for col,width in izip_longest(line,widths, fillvalue=""):
                    outfile.write("%s%s%s|" %(' '*((width-len(col))/2), col, ' '*((width+1-len(col))/2)))
                outfile.write('\n+')
                for width in widths:
                    outfile.write('-'*width + "+")
                outfile.write('\n')

def getWidths(infilepath, delim):
    answer = defaultdict(int)
    with open(infilepath) as infile:
        for line in infile:
            cols = line.strip().split(delim)
            lens = map(len, cols)
            for i,l in enumerate(lens):
                if answer[i] < l:
                    answer[i] = l

    return [answer[k] for k in sorted(answer)]

if __name__ == "__main__":
    print 'starting'

    infilepath = 'testin'
    outfilepath = 'testout'
    tabularize(infilepath, outfilepath, '...', False)

    print 'done'
于 2013-11-05T07:26:50.413 回答