因此,我设法使用填充来对齐几个变量/文本。但是,我的代码涉及更改列表中的变量,因此会更改长度,并影响我的列的对齐。
product_names = ["hamburger", "cheeseburger", "small fries"]
product_costs = [0.99, 1.29, 1.49]
product_quantity = [10,5,20]
print(format("Product",'<10s'),"Price","Quantity",sep = 't')
for x in range(len(product_names)):
print(format(product_names[x],'<16s'),end ='')
print(product_costs[x],product_quantity[x],sep = 't')
我得到的输出是:
Product Price Quantity
hamburger 0.99 10
cheeseburger 1.29 5
small fries 1.49 20
但是,如果我将芝士汉堡更改为更长的东西。例如双芝士汉堡。生病了。
Product Price Quantity
hamburger 0.99 10
double cheeseburger1.29 5
small fries 1.49 20
如何保持列保持一致?
要么为文本分配更多空间,要么截断文本:
def truncate(s):
if len(s) >= 16:
return s[:13] + '...'
else:
return s
print(format(truncate(product_names[x]),'<16s'),end ='')
这是一个使用列输入来打印表的函数,以确定每列的宽度。它通过使用为列数复制的默认字符串来工作;然后将其格式化为具有带有每列最大字符的宽度以及间隙的字符串格式。然后将该字符串格式化每行以打印行。
如果提供了header
列表,它将相应地调整宽度并也打印出来。gap
指示每列之间有多少个空间。
def table_printer(*columns, header=None, gap=1):
print_header = False
if header is None:
header = ['']*len(columns)
else:
assert len(header)==len(columns), (
"Must have same number of headers as columns."
)
print_header = True
col_widths = [max(map(len, map(str, c+[h])))+gap for c,h in zip(columns, header)]
width_formatter = '{{:<{}}}'*len(columns)
row_formatter = width_formatter.format(*col_widths)
if print_header:
print(row_formatter.format(*header))
for row in zip(*columns):
print(row_formatter.format(*row))
product_names = ["hamburger", "cheeseburger", "small fries"]
product_costs = [0.99, 1.29, 1.49]
product_quantity = [10,5,20]
table_printer(product_names, product_costs, product_quantity,
header=['Product', 'Price', 'Quantity'],
gap=3)
# prints:
Product Price Quantity
hamburger 0.99 10
cheeseburger 1.29 5
small fries 1.49 20