How to repeat the format in @printf?

Yes, but that generates strings. format can operate on an IO, so it wouldn’t be too hard to define such a function that doesn’t go via strings at all.

1 Like

You are right. For avoiding even the intermediate strings, something like

function join2(io, f, itr, delim, last = delim)
    for (i, a) in enumerate(a)
        i == 0 || print(io, delim)
        f(io, a)
    print(io, last)

which takes a two-argument function but encapsulates the logic of join would be nice.


Swap the first two arguments and you can do

open("file.tsv", "w") do file
    join(file, numbers, delimiter) do io, x
        format(io, fmt, x)

Not sure why you’d want to, but it looks pretty cool.

1 Like

You can use the splat operator.

Printf.format(io, f, a...)
1 Like

I’m confused about this one. When I tried it I got

julia> x=rand(3);

julia> fmt=Printf.Format("%.2f");

julia> Printf.format(fmt,x...)
ERROR: ArgumentError: mismatch between # of format specifiers and provided args: 1 != 3

What have I missed?

Your format string only has one specifier, so it will only work on one argument. Depending on what output you’re expecting, there’s options like

julia> fmt=Printf.Format("%.2f"^3); # equivalent to "%.2f%.2f%.2f"

julia> Printf.format(fmt, x...)


julia> fmt=Printf.Format("%.2f");

julia> Printf.format.(Ref(fmt),x)
3-element Vector{String}:
1 Like