tags:

views:

400

answers:

4

I have a data table 44 columns wide that I need to write to file. I don't want to write:

outfile.write("%i,%f,%f,$f ... )\n" % (i, a,b,c ...))

In Fortran you can specify multiple format specifiers easily:

write (*,"(3f8.3)") a,b,c

Is there a similar capability in Python?

+2  A: 

Are you asking about

format= "%i" + ",%f"*len(row) + "\n"
outfile.write( format % ([i]+row))
S.Lott
+11  A: 
>>> "%d " * 3
'%d %d %d '
>>> "%d " * 3 % (1,2,3)
'1 2 3 '
dwc
Thanks for the post, I didn't know this. It also worked when I tried it as part of a print in a program: print "%d " * 3 % (1, 2, 3)
PTBNL
Note that the * operator isn't specific to format specifiers; it tells Python to duplicate the preceding sequence X times. Since a string is a sequence, and format specifiers are just strings ...
Chris B.
A: 

Is not exactly the same, but you can try something like this:

values=[1,2.1,3,4,5]  #you can use variables instead of values of course
outfile.write(",".join(["%f" % value for value in values]));
Adrian Mester
A: 

Note that I think it'd be much better to do something like:

outfile.write(", ".join(map(str, row)))

...which isn't what you asked for, but is better in a couple of ways.

James Antill