Nathan Boyer
Nathan Boyer

Reputation: 1474

What is the proper way to repeat a format string in Julia?

I have an array of floats x and would like to print the last row to screen as integers. The following code does not work and yields ArgumentError: @printf: first or second argument must be a format string. How can I print with a variable format string?

using Printf
@printf("%i "^length(x[end,:]), x[end,:]...)

Upvotes: 2

Views: 777

Answers (2)

phipsgabler
phipsgabler

Reputation: 20950

Using @eval to compile a simple print statement every time is really a bad approach. There's no functionality for dynamic format strings etc. because Julia has a wide range of other nice tools to achieve the same things:

julia> join(stdout, (round(Int, y) for y in x[end, :]), " ")
1 0 1

And printing an array is really not what printf is made for (not even in C).

That is not to say that a printf function taking a runtime format string wouldn't be a nice thing, but see here for the reasoning behind making it a macro. I've never missed printf, but in case you really do, there's Formatting.jl, which provides all functinality you can imagine.

Upvotes: 2

San
San

Reputation: 463

Our "constants" are still run-time values – they are write-once rather than compile-time constants like in C.

As a hack until julia gets real support for runtime format strings, this works:

using Printf
const fmt = "%i "^length(x[end,:])
@eval @printf($fmt, x[end,:]...)

Upvotes: 0

Related Questions