問題描述
為了打印表格數據的標題,我只想使用一個格式字符串 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]}
等嘗試給出 KeyError
或 keyword 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!
這篇關于Python格式字符串中的寬度變量的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!