有人指出你的问题可能是重复的,但有问题的答案看起来有点旧......自从引入新的字符串格式mini语言,你可以单独使用str.format
来做这种事情。
假设您的列表看起来像:
data = [
["John" , 15.00, 1.20, 10.00, 8.00],
["Robert", 45.00, 6.70, 24.00, 14.00],
["Duncan", 10.00, 5.40, 5.00, 10.00],
["Steven", 30.00, 6.50, 30.00, 16.00],
]
您可以使用格式方法:
# Headers, centered
print("{: ^15s} {: ^15s} {: ^15s} {: ^15s} {: ^15s}".format(
"Name", "Age", "Height", "Pay Rate", "Grade")
)
# Dashes (not very readable, but I'm lazy)
print(" ".join([("-" * 15)] * 5))
# Lines
for line in data:
print("{:15s} {: 15.2f} {: 15.2f} {: 15.2f} {: 15.2f}".format(*line))
的格式规范(见format specification mini-language):
format_spec ::= [[fill]align][sign][#][0][width][,][.precision][type]
fill ::= <any character>
align ::= "<" | ">" | "=" | "^"
sign ::= "+" | "-" | " "
width ::= integer
precision ::= integer
type ::= (pretty much like printf)
^
手段居中。
结果应该是这样的:
Name Age Height Pay Rate Grade
--------------- --------------- --------------- --------------- ---------------
John 15.00 1.20 10.00 8.00
Robert 45.00 6.70 24.00 14.00
Duncan 10.00 5.40 5.00 10.00
Steven 30.00 6.50 30.00 16.00
使这一短多可重复使用的留作练习。
你的名单是怎样的? – spiehr
在继续之前,我会建议您使用字典而不是列表。当你开始填充表格时,可读性更强,更容易混淆。 '人'['John'] ['Height']'比'people [0] [1]'更透明。然后,“对于人:对attribs中的attrib:print(人[person] [attrib])'加上任何格式化。 – OJFord