【问题标题】:How to align only the 2nd and 4th column of a table?如何仅对齐表格的第 2 列和第 4 列?
【发布时间】:2016-12-06 07:54:58
【问题描述】:

我知道如何对齐表格中的所有字段:

r=["this is my text of line1", 
   "and this was one more line", 
   "another line of text to display"]

 import re
 splitter = "\s+"
 columnstotal = []
 for i in range(0,len(r)):
     #remove splitter
     columns = re.split(splitter, r[I])
     #keep splitter
     columns = re.split('(' + splitter + ')', r[i])
     columnstotal.append(columns)

并使用 .format() 再次显示列

但是如何只对齐 2 列:
第 2 列(右对齐)+ 第 4 列(左对齐)?

预期输出

     this is| my  |text of line1
    and this| was |one more line
another line| of  |text to display

【问题讨论】:

  • 请提供更多输入数据,以及您希望在输出中看到的确切结果。
  • 另外,作为一个旁注,如果你想要r的一部分,你不会在Python中对r的长度做一个数字for:你可以简单地做@987654326 @
  • @jsbueno,我更新了我的问题
  • @jsbueno,你还在吗?

标签: python list python-3.x alignment multiple-columns


【解决方案1】:

您的拆分器没有分成 3/4 部分...您的示例显示 3 列。
因此,假设您修复了拆分器并最终得到:

columnstotal = [['this is', 'my', 'text of line1'],
                ['and this', 'was', 'one more line'],
                ['another line', 'of', 'text to display']]
width0 = max(len(d[0]) for d in s)
width1 = max(len(d[1]) for d in s)
for row in columnstotal:
    print("{:>{width0}}| {:<{width1}} |{}".format(*row, width0=width0, width1=width1))

输出:

     this is| my  |text of line1
    and this| was |one more line
another line| of  |text to display

【讨论】:

  • 感谢您的回答。我的分离器是要使用的。我有要划分的文本行。我的问题是我不知道如何获得您的答案中的列总数。你知道如何在第 2 次和第 4 次出现 "\s+" 时分割一行吗?顺便说一句,感谢您的其余回答。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-14
  • 1970-01-01
  • 1970-01-01
  • 2017-10-11
相关资源
最近更新 更多