Can I define string as "%Fmt" in Printf?

Sorry for another stupid question.
It is a little similar with How to repeat the format in @printf? - #12 by CRquantum
However i want to be more creative by design my own fmts in Printf.

The idea is simply, I looked at Printf · The Julia Language
There is a simply example there,

@printf("%f %F %f %F", Inf, Inf, NaN, NaN)

output is
Inf Inf NaN NaN

Now, my idea is simply, it looks like “%f %F %f %F” is a string,
so I think i can do

s = string("%f %F %f %F")
@printf(s, Inf, Inf, NaN, NaN)

It should give the same results.
But it gives me error.
However I think if it works it can be powerful because we can define anything using string concatenation like ^ * etc.

Could anyone give some hints, is it possible to do things like above?

I am thinking I may do thinks like

define something
@printf( "$(something)", Inf, Inf, NaN, NaN)

Is it possible?

Thank you very much in advance.

It seems to be the same problem with the same solution as in the other post:

s = Printf.Format("%f %F %f %F");
Printf.format(s,  Inf, Inf, NaN, NaN)

Thank you very much. Sorry I was a little sleepy and asked a stupid question again.
I see, the great thing of Printf.Format is that it allows me to put string() inside, like,

s = Printf.Format(string("%f"^4,"%f"^4))

So can define anything.

May I ask, how to use or is it possible to use Printf.format to write the contents in a txt file, say AA.txt?

A very basic example below.
Recommend you search discourse for more complete examples.

str = Printf.format(s,  Inf, Inf, NaN, NaN)

io = open("fileout.txt", "a");
write(io, str);

or better:

io = open("fileout.txt", "a");
    Printf.format(io, s, Inf, Inf, NaN, NaN)

With @sprintf it is more compatible with “R”…and IMO simpler.

1 Like

Your example does not seem to answer OP’s question. See the post linked by OP, the eval method and this comment.

Maybe the do-block form of open would be better to suggest?

open("fileout.txt", "a") do io
    Printf.format(io, s, Inf, Inf, NaN, NaN)

That way the file handle is still closed in case format throws an exception (using a try-finally block under the hood).


While format strings are a powerful DSL, I would stop short of including conditionals and control flow and use Julia instead. That is, if you need to construct a format string on the fly, just encapsulate the logic in a function that branches to the appropriate @printf "%f" value or @printf "%F" value.


Thank you very much indeed!

May I ask one more thing, if I set array A as

A = [Inf, Inf, NaN, NaN] 

can I just print this array in a way like

Printf.format(io, s, A)  ?

I think this should work:

Printf.format(io, s, A…)
1 Like