我知道如何对齐表格中的所有字段:
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
答案 0 :(得分: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