繁体   English   中英

Python-以空格格式打印数字

[英]Python - Printing numbers with spacing format

假设我有一个数字数组

list = [(4, 3, 7, 23),(17, 4021, 4, 92)]

我想以某种方式打印数字,以便输出看起来像这样:

[   4  |   3  |   7  |  23  ] 
[  17  | 4021 |   4  |  92  ]

数字尽可能居中并且“ |”之间有足够的空间 允许一个4位数的数字,在两侧各有两个空格。

我该怎么做?

谢谢。

str.center可以使事情变得容易。

for i in list:
    print '[ ' + ' | '.join([str(j).center(4) for j in i]) + ' ]'

输出:

[  4   |  3   |  7   |  23  ]
[  17  | 4021 |  4   |  92  ]

如果您需要其他解决方案,可以使用str.format

for i in list:
    print '[ ' + ' | '.join(["{:^4}".format(j) for j in i]) + ' ]'

输出:

[  4   |  3   |  7   |  23  ]
[  17  | 4021 |  4   |  92  ]

您也可以使用第三方,例如PrettyTabletexttable 使用texttable示例:

import texttable

l = [(4, 3, 7, 23),(17, 4021, 4, 92)]

table = texttable.Texttable()
# table.set_chars(["", "|", "", ""])
table.add_rows(l)

print(table.draw())

将产生:

+----+------+---+----+
| 4  |  3   | 7 | 23 |
+====+======+===+====+
| 17 | 4021 | 4 | 92 |
+----+------+---+----+

这里:

list = [[4, 3, 7, 23],[17, 4021, 4, 92]]

for sublist in list:
    output = "["
    for index, x in enumerate(sublist):
        output +='{:^6}'.format(x) 
        if index != len(sublist)-1:
            output += '|'  
    output +=']'
    print output 

输出:

[  4   |  3   |  7   |  23  ]
[  17  | 4021 |  4   |  92  ]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM