Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
117 views
in Technique[技术] by (71.8m points)

python - Using .format() to format a list with field width arguments

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

Given

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

and

(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

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.

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

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:UserslablaDesktop>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:UserslablaDesktop>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

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

My question is:

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The error message

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

works fine.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...