为了打印表格数据的标题,我只想使用一种格式字符串 line
和一种列宽规范 w1, w2, w3
(甚至 w = x, y, z
如果可能的话。)
我看过this但是 tabulate
等不要让我像 format
那样证明列中的内容。
这种方法有效:
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表达式
。
我还认为 w1=w1, w2=w2, w3=w3
不是很简洁。有没有更好的办法?
最佳答案
现在使用 f 字符串格式变得非常容易。
如果你正在使用
print(f'{token:10}')
并且您希望 10 成为另一个变量(例如所有标记的最大长度),您可以这样写
print(f'{token:{maxTokenLength}}')
换句话说,将变量包含在 {}
在您的特定情况下,您只需要这个。
head = 'eggs', 'bacon', 'spam'
w1, w2, w3 = 8, 7, 10 # column widths
print(f' {head[0]:>{w1}} {head[1]:>{w2}} {head[2]:>{w3}}')
print(f' {"="*w1:>{w1}} {"="*w2:>{w2}} {"="*w3:>{w3}}')
产生
eggs bacon spam
======== ======= ==========
关于python - Python 格式字符串中的宽度变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38159243/