字符串格式对齐

时间:2013-05-30 04:59:47

标签: python python-3.x

我对如何解决这种格式问题感到困惑。我怀疑这是因为存在两个变量而不是一个变量,而这些变量又全部抛出。

这是我目前的输出..

Bin Range    Count
0-9           1   
20-29          1 

我正努力实现..

Bin range    Count
0-9            1
20-29          1

此段的代码是..

counter = collections.Counter()
for py_filename in glob.glob('*.py'):
    with open(py_filename) as f:
        linecount = sum(1 for line in f)
        counter[linecount//10] += 1

print('\n{0}    {1}'.format('Bin Range', 'Count'))

for i,n in sorted(counter.items()):
    print('{}-{:<12}{:<4}'.format(i * 10, (i + 1) * 10 - 1, n))

我假设如果0-9部分都是一个变量,那么这不是问题,但是有一种方法可以在格式规则下分组两个变量,或者我只是需要找出一种更有效的方法来处理我的结果。

欢呼帮助!

2 个答案:

答案 0 :(得分:2)

为什么不使用子格式,如:

for i,n in sorted(counter.items()):
    binrange='{}-{}'.format(i*10, (i + 1) * 10 - 1)
    print('{:<12}{:<4}'.format(binrange, n))

答案 1 :(得分:1)

您可以使width变量取决于第一项的字符串长度:

In [1]: items = [[0, 9, 1], [20, 29, 1]]

In [2]: for x, y, z in items:
   ...:     print '{}-{:<{width}}{}'.format(x, y, z, width=10-len(str(x)))
   ...:     
0-9        1
20-29      1