Python3.2 Str.format值重复

Pon*_*nml 5 python string format

我正在为程序生成特定格式的输入文件,并使用一个小的python tkinter GUI前端来执行此操作.旧代码使用了fortran格式语句.除非已经有一个python的直接转换函数集(我还没有找到),我认为python的格式化可以完成这项工作.一般情况下它可以,但我找不到重复某个值的方法:

例如,在fortran中:

FORMAT (2A1, I3, **12I5**, F8.3, A7). The "12I5" statement translates to 12 integer values of width 5.
Run Code Online (Sandbox Code Playgroud)

我知道我的格式调用可以在文本上有12个项目(例如:) ...{0:5d}, {1:5d}, {2:5d}....,但我想知道是否有一种方法可以像上面的fortran示例那样使用简化形式.

有没有我错过的,或者这是不可能的,我必须明确写出格式中的每个项目?

-Cheers,克里斯.

编辑 这是我目前正在做的一个更清晰的例子:

>>> ---tester = ["M", "T", 1111, 2222, 234.23456, "testing"]    
>>> ---fmt = "{0:1}{1:1}, {2:3d}, {3:5d}, {4:8.3F}, {5:>7}"    
>>> ---print(fmt.format(*tester))    
MT,  13,  1234,  234.235, testing
Run Code Online (Sandbox Code Playgroud)

我希望能够

>>> ---tester = ["M", "T", 1111, **2222, 3333, 4444**, 234.23456, "testing"]    
>>> ---fmt = "{0:1}{1:1}, {2:3d}, **3*{3:5d}**, {4:8.3F}, {5:>7}"    
>>> ---print(fmt.format(*tester))       
Run Code Online (Sandbox Code Playgroud)

nco*_*lan 4

正如 ninjagecko 所建议的,您希望分段构建格式字符串。

正如我所做的那样,使用隐式字段编号有助于简化这一过程,尽管这并不是绝对必要的(显式编号只是变得更加冗长,以确保数字对齐)。混合旧式和新式字符串格式还意味着我们可以跳过一些繁琐的特殊字符转义。

subfmt = ", ".join(["{:5d}"]*3)
fmt = "{:1}{:1}, {:3d}, %s, {:8.3F}, {:>7}" % subfmt
tester = ["M", "T", 1111, 2222, 3333, 4444, 234.23456, "testing"]

>>> print(fmt)
{:1}{:1}, {:3d}, {:5d}, {:5d}, {:5d}, {:8.3F}, {:>7}
>>> print(fmt.format(*tester))
MT, 1111,  2222,  3333,  4444,  234.235, testing
Run Code Online (Sandbox Code Playgroud)