Python:想要在列中均匀显示内容

时间:2013-11-05 07:21:49

标签: python string string-formatting

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

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 |

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

我有办法实现这个目标吗?

先谢谢

3 个答案:

答案 0 :(得分: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 |

答案 1 :(得分: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)

Whatevers,这将是输出:

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

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

答案 2 :(得分: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'