Variables for width in Python format string(Python格式字符串中的宽度变量)
问题描述
为了打印表格数据的标题,我只想使用一个格式字符串 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格式字符串中的宽度变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Python格式字符串中的宽度变量
基础教程推荐
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- Discord.py 缺少必需的参数 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
