Python格式字符串中的宽度变量

2022-01-15 00:00:00 python string format

问题描述

为了打印表格数据的标题,我只想使用一个格式字符串 line 和一个列宽规范 w1, w2, w3 (如果可能的话,甚至是 w = x, y, z.)

In order to print a header for tabular data, I'd like to use only one format string line and one spec for column widths w1, w2, w3 (or even w = x, y, z if possible.)

我看过 this 但 tabulate 等不要让我像 format 那样证明列中的内容.

I've looked at this but tabulate etc. don't let me justify things in the column like format does.

这种方法有效:

head = 'eggs', 'bacon', 'spam'  
w1, w2, w3 = 8, 7, 10  # column widths  
line = '  {:{ul}>{w1}}  {:{ul}>{w2}}  {:{ul}>{w3}}'  
under = 3 * '='  
print line.format(*head, ul='', w1=w1, w2=w2, w3=w3)  
print line.format(*under, ul='=', w1=w1, w2=w2, w3=w3)  

我必须在格式字符串中有单独的名称作为宽度 {w1}, {w2}, ...吗?{w[1]}{w[2]} 等尝试给出 KeyErrorkeyword can't be an表达式.

Must I have individual names as widths {w1}, {w2}, ... in the format string? Attempts like {w[1]}, {w[2]}, give either KeyError or keyword can't be an expression.

另外我认为 w1=w1, w2=w2, w3=w3 不是很简洁.有没有更好的办法?

Also I think the w1=w1, w2=w2, w3=w3 is not very succinct. Is there a better way?


解决方案

这是 jonrsharpe 对我的 OP 的评论,旨在可视化正在发生的事情.

This is jonrsharpe's comment to my OP, worked out so as to visualise what's going on.

line = '  {:{ul}>{w1}}  {:{ul}>{w2}}  {:{ul}>{w3}}'
under = 3 * '_'

head = 'sausage', 'rat', 'strawberry tart'

# manual dict 
v = {'w1': 8, 'w2':5, 'w3': 17}
print line.format(*under, ul='_', **v)

# auto dict
widthl = [8, 7, 9]
x = {'w{}'.format(index): value for index, value in enumerate(widthl, 1)}
print line.format(*under, ul='_', **x)     

关键是我希望能够快速重新排列标题,而无需调整格式字符串.auto dict 很好地满足了这个要求.

The point is that I want to be able to quickly rearrange the header without having to tweak the format string. The auto dict meets that requirement very nicely.

至于以这种方式填充字典:哇!

As for filling a dict in this way: WOW!

相关文章