【问题标题】:Python - Printing numbers with spacing formatPython - 以间距格式打印数字
【发布时间】:2017-01-01 00:54:29
【问题描述】:

假设我有一个数字数组

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

我想以这样的方式打印数字,使输出看起来有点像这样:

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

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

我该怎么做?

谢谢。

【问题讨论】:

  • 调用你的变量list可能不是一件好事

标签: python string list format number-formatting


【解决方案1】:

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  ]

【讨论】:

  • 你可能想做的不是硬编码4,_list = [(4, 3, 7, 23),(17, 4021, 4, 92)] ; lst = [len(str(x)) for i in _list for x in i] ; _width = max(lst) ;
【解决方案2】:

这里:

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  ]

【讨论】:

    【解决方案3】:

    您还可以使用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 |
    +----+------+---+----+
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-04-20
      • 1970-01-01
      • 1970-01-01
      • 2017-08-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多