使用.format()格式化带有字段宽度参数的列表 [英] Using .format() to format a list with field width arguments

查看:68
本文介绍了使用.format()格式化带有字段宽度参数的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近(最终是?)开始使用.format(), 对此可能有一个晦涩的问题.

I recently (finally?) started to use .format() and have a perhaps a bit obscure question about it.

给予

res = ['Irene Adler', 35,  24.798]

(1) print('{0[0]:10s} {0[1]:5d} {0[2]:.2f}'.format(res))
(2) print('{:{}s} {:{}d} {:{}f}'.format(res[0], 10, res[1], 5, res[2], .2))

做得好,而且都可以打印:

work great and both print:

Irene Adler    35 24.80
Irene Adler    35 24.80

我不知道我可以像(1)中那样处理列表,这很简洁.一世 以前曾使用过旧的%格式查看过字段宽度参数(2).

I didn't know that I could deal with lists as in (1) which is neat. I had seen about field width arguments (2) with the old % formatting before.

我的问题是想要做这样的事情,将(1)和(2)结合起来:

My question is about wanting to do something like this which combines (1) and (2):

(3) print('{0[0]:{}s} {0[1]:{}d} {0[2]:{}f}'.format(res, 10, 5, .2))

但是,我无法做到这一点,而且我一直无法弄清楚 如果可能的话,从文档中获取.只是很好 提供要打印的列表以及width的参数.

However, I am unable to do this, and I haven't been able to figure out from the documentation if this even possible. It would be nice to just supply the list to be printed, and the arguments for width.

顺便说一句,我也尝试了这个(没有运气):

By the way, I also tried this (w/o luck):

args = (10, 5, .2)
(4) print('{0[0]:{}s} {0[1]:{}d} {0[2]:{}f}'.format(res, args))

在两种情况下,我都得到了:

In both instances I got:

D:\Users\blabla\Desktop>python tmp.py
Traceback (most recent call last):
  File "tmp.py", line 27, in <module>
    print('{0[0]:{}s} {0[1]:{}d} {0[2]:{}f}'.format(res, 10, 5, .2))
ValueError: cannot switch from manual field specification to automatic field numbering

D:\Users\blabla\Desktop>python tmp.py
Traceback (most recent call last):
  File "tmp.py", line 35, in <module>
    print('{0[0]:{}s} {0[1]:{}d} {0[2]:{}f}'.format(res, args))
ValueError: cannot switch from manual field specification to automatic field numbering

我还尝试使用zip()来组合这两个序列而没有运气.

I also tried using zip() to combine the two sequences without luck.

我的问题是:

我可以根据自己的尝试指定要有效打印的列表吗? 未能在(3)和(4)中完成(显然,如果可能的话,我是 没有使用正确的语法),如果可以,怎么办?

Can I specify a list to be printed effectively doing what I was trying to unsuccessfully do in (3) and (4) (clearly if this is possible, I'm not using the right syntax) and if so, how?

推荐答案

错误消息

ValueError: cannot switch from manual field specification to automatic field numbering

这说明了一切:您需要在任何地方提供明确的字段索引,并且

pretty much says it all: You need to give explicit field indices everwhere, and

print('{0[0]:{1}s} {0[1]:{2}d} {0[2]:{3}f}'.format(res, 10, 5, .2))

工作正常.

这篇关于使用.format()格式化带有字段宽度参数的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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