Lev*_*von 47 python list string-formatting
我最近(终于?)开始使用.format()并且有一个可能有点模糊的问题.
特定
res = ['Irene Adler', 35, 24.798]
Run Code Online (Sandbox Code Playgroud)
和
(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))
Run Code Online (Sandbox Code Playgroud)
工作得很好,同时印刷:
Irene Adler 35 24.80
Irene Adler 35 24.80
Run Code Online (Sandbox Code Playgroud)
我不知道我可以像(1)那样处理清单.我之前看到过带有旧%格式的字段宽度参数(2).
我的问题是想要做这样的事情,它结合了(1)和(2):
(3) print('{0[0]:{}s} {0[1]:{}d} {0[2]:{}f}'.format(res, 10, 5, .2))
Run Code Online (Sandbox Code Playgroud)
但是,我无法做到这一点,我无法从文档中找出这是否可行.提供要打印的列表和宽度的参数会很好.
顺便说一句,我也试过这个(没有运气):
args = (10, 5, .2)
(4) print('{0[0]:{}s} {0[1]:{}d} {0[2]:{}f}'.format(res, args))
Run Code Online (Sandbox Code Playgroud)
在这两种情况下,我得到:
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
Run Code Online (Sandbox Code Playgroud)
我也尝试过使用zip()这两个序列而没有运气.
我的问题是:
我是否可以指定一个列表,以便有效地执行我在(3)和(4)中尝试不成功的情况(如果可能的话,我没有使用正确的语法),如果是这样,怎么做?
Sve*_*ach 65
错误消息
ValueError: cannot switch from manual field specification to automatic field numbering
Run Code Online (Sandbox Code Playgroud)
几乎说了一切:你需要在任何地方提供明确的字段索引,并且
print('{0[0]:{1}s} {0[1]:{2}d} {0[2]:{3}f}'.format(res, 10, 5, .2))
Run Code Online (Sandbox Code Playgroud)
工作良好.
| 归档时间: |
|
| 查看次数: |
50226 次 |
| 最近记录: |