8

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?

4 Answers 4

22
>>> "%d " * 3
'%d %d %d '
>>> "%d " * 3 % (1,2,3)
'1 2 3 '
Sign up to request clarification or add additional context in comments.

3 Comments

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)
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 ...
@ChrisB.: Not "duplicate X times", but "multiply X times", I believe :) The former could be understood as if "%d " * 3 would be equal to ((("%d " * 2) * 2) * 2).
3

Are you asking about

format= "%i" + ",%f"*len(row) + "\n"
outfile.write( format % ([i]+row))

Comments

0

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.