我正在尝试将表格格式化为:
0 Banana 1 Apple 2 Orange
3 Pear 4 Grape 5 Coconut
6 Test1 7 Test2 8 Test3
9 Test4 10 TestTest5 11 TestTest6
项目之间的最小空格数应为4.从0 Banana到1 Apple,以及10 TestTest5和11 TestTest6。左对齐。
我正在尝试使用此字符串格式化...
i = 0
line = ""
whole = ""
for n,m in enumerate(grid):
if i <3:
line += "%s %-13s" % (n, m)
else:
whole += "%s\n"%line
line = "%s %-13s" % (n, m)
i = 0
i += 1
whole += "%s\n" % line
whole = whole.replace("'", "")
whole = whole.replace('"', "")
print whole
但结果并不完全相同
0 Banana 1 Apple 2 Orange
3 Pear 4 Grape 5 Coconut
6 Test1 7 Test2 8 Test3
9 Test4 10 TestTest5 11 TestTest6
我怎样才能做到这一点?我想我需要一些方法来改变%-13s,具体取决于上面/下面的行的长度。
答案 0 :(得分:1)
您可以在格式化之前先连接数字和字符串:
for n, m in enumerate(grid):
if not n or n % 3:
line += "%-15s" % (str(n) + ' ' + m)
else:
whole += "%s\n" % line
line = "%-15s" % (str(n) + ' ' + m)
产生:
0 Banana 1 Apple 2 Orange
3 Pear 4 Grape 5 Coconut
6 Test1 7 Test2 8 Test3
9 Test4 10 TestTest5 11 TestTest6
或者您可以将数字格式化为两个位置,右对齐:
for n, m in enumerate(grid):
if not n or n % 3:
line += "%2d %-12s" % (n, m)
else:
whole += "%s\n" % line
line = "%2d %-12s" % (n, m)
产生:
0 Banana 1 Apple 2 Orange
3 Pear 4 Grape 5 Coconut
6 Test1 7 Test2 8 Test3
9 Test4 10 TestTest5 11 TestTest6
答案 1 :(得分:0)
也许是这样的(如果您希望列之间有4个空格,具体取决于每列的最长元素):
#! /usr/bin/python3
def printGrid (it, columns):
items = ['{} {}'.format (idx, item) for idx, item in enumerate (it) ]
maxWidths = [max (len (item) for item in items [col::columns] ) for col in range (columns) ]
padded = [item + ' ' * (4 + maxWidths [idx % columns] - len (item) ) for idx, item in enumerate (items) ]
while True:
if not padded: break
items = padded [:columns]
padded = padded [columns:]
print (' '.join (items) )
data = 'Banana,Apple,Orange,Pear,Grape,Coconut,Test1,Test2,Test3,Test4,TestTest5,TestTest6,Test7'.split (',')
printGrid (data, 3)
或使用内置格式:
def printGrid (it, columns):
items = ['{} {}'.format (idx, item) for idx, item in enumerate (it) ]
maxWidths = [max (4 + len (item) for item in items [col::columns] ) for col in range (columns) ]
formatStr = ''.join ('{{:<{}}}'.format (width) for width in maxWidths)
while True:
if not items: break
line = items [:columns]
items = items [columns:]
while len (line) < columns: line.append ('')
print (formatStr.format (*line) )
说明:
items
构建项目列表,格式为index + space + item
maxWidth
计算每列的最大宽度
(第1段摘要:) padded
根据其列
(第2段摘要:) formatStr
执行您要求的内容:“根据上述/下方行的长度更改%-13s”
(2nd snippet :) while len...
:填充行,因此formatStr获取正确数量的参数
剩下的就是打印。