How to use @sprintf with "parametric" format string?

Is there a way to use @sprintf with “parametric” format string? or it has to be hardcoded?
This is an example:

julia> @sprintf(“test: %s”, “test”)
“test: test”
julia> fmt = “test: %s”; @sprintf(fmt, “test”)
ERROR: LoadError: ArgumentError: @sprintf: first argument must be a format string

In Julia 1.6 you can do this:

julia> import Printf: Format, format

julia> function test(n,x)
           f = Format("%10.$(n)f")
           format(f,x)
       end
test (generic function with 1 method)

julia> test(3,1.0)
"     1.000"

julia> test(5,1.0)
"   1.00000"

There is also the Formatting.jl package: https://github.com/JuliaIO/Formatting.jl

2 Likes

Is there not a solution in which I can simply provide a variable holding the format string? String interpolation does not work either.

Sure there is:

julia> fmt = "test: %s"; Printf.format(Printf.Format(fmt), "test")
"test: test"

(However, it’s faster if you use a literal format string ala @sprintf, since that allows the format to be parsed at compile time. What are you trying to accomplish?)

1 Like

Why doesn’t Printf.jl make life easier for users and define such a printf() function?

using Printf
fmt = "test: %.3f"
printf(s, x) = Printf.format(Printf.Format(s), x)
printf(fmt, π)    # "test: 3.142"

This would also allow:

n = 2
printf("test2: %.$(n)f", π)    # "test2: 3.14"

Probably because you should really be using @printf if you can (or the Printf.format"foo" string macro), due to the aforementioned compile-time format parsing. A runtime-constructed format string should be a rarity in practice.

1 Like