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

3
为了打印表格数据的标题,我想使用一个格式字符串 line 和一个规范来指定列宽 w1, w2, w3(如果可能的话,甚至可以使用 w = x, y, z)。
我查看了这个,但是像 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关键字不能是表达式
此外,我认为 w1=w1, w2=w2, w3=w3 不太简洁。有更好的方法吗?

2
为什么不使用字典 - w = {'w1': 8, 'w2': 7, 'w3': 10},然后调用 line.format(..., **w)。你甚至可以根据 [8, 7, 10] 动态构建字典 - w = {'w{}'.format(index): value for index, value in enumerate([8, 7, 10], 1)} - jonrsharpe
@jonrsharpe 谢谢!我得承认,在理解你的自动字典填充器之前,我花了一些时间学习。另外请看下面... - RolfBly
3个回答

6

使用f-string格式现在变得非常容易。

如果您曾经使用过

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
  ========  =======  ==========

1

如果您定义了w = 8, 7, 10并将w作为关键字参数传递,那么指定w[0]w[1]w[2]应该是有效的:

>>> head = 'eggs', 'bacon', 'spam'
>>> w = 8, 7, 10  # <--- list is also okay
>>> line = '  {:{ul}>{w[0]}}  {:{ul}>{w[1]}}  {:{ul}>{w[2]}}'
>>> under = 3 * '='
>>> print line.format(*head, ul='', w=w)  # <-- pass as a keyword argument
      eggs    bacon        spam
>>> print line.format(*under, ul='=', w=w)  # <-- pass as a keyword argument
  ========  =======  ==========

1
这是jonrsharpe对我的原始帖子的评论,为了更好地理解发生了什么而制作出来的可视化效果。
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非常完美地满足了这个要求。
至于以这种方式填充字典:哇!

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接