Repeating Python3.2 Str.format Value

I create specially formed input files for the program and use the small python tkinter GUI interface for this. The old code used fortran formatting instructions. If I don't already have a direct set of functions for python (which I did not find), I decided that formatting in python would do the job. In general, this is possible, but I cannot find a way to repeat a specific value:

For example, in fortran:

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

I know that in text form I could have 12 elements (for example:) ...{0:5d}, {1:5d}, {2:5d}...., but I was wondering if there is a simplified form method like the fortran example above.

Is there something I missed, or is it impossible, and should I explicitly write out each element in a format?

-Cheers, Chris.

edit Here is a clearer example of what I'm doing now:

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

I would like to be able

>>> ---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))       
+5
source share
2 answers

As ninjagecko suggested, you want to build your format string in pieces.

Using implicit field numbering, as I did, helps simplify this, although it is not strictly necessary (explicit numbering just gets a little more detail, making sure the numbers are the same). Mixing old-style and new-style formatting also means we can skip some tedious escaping of special characters.

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
+4
source

You could generate part of your format string like this (adapt as you wish):

>>> ','.join(['%s']*5)
'%s,%s,%s,%s,%s'

>>> ','.join(['%i']*5) % (1,2,3,4,5)
'1,2,3,4,5'

'%i '*10 ( , )

, , str.format(http://docs.python.org/library/stdtypes.html#str.format), , http://docs.python.org/library/string.html#formatstrings. , , , , . . .

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

:

'MT, 1111,  2222,  3333,  4444,  234.235, testing'

(edit2: ncoghlan, )

+2

All Articles