Python格式字符串中的width变量 [英] Variables for width in Python format string

查看:87
本文介绍了Python格式字符串中的width变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了打印表格数据的标题,我只想使用一种格式字符串 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.)

我查看了,但制表等.我不能像 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不能作为表达式.

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格式字符串中的width变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆