@sprintf() does not work inside a for loop

@sprintf() does not work inside for loop. I wonder why.

julia> using Printf

julia> for k in 1:10
           @sprintf("%.4f, ", sin(k))
       end

julia> @sprintf("%.4f, ", sin(2))
"0.9093, "

julia> for k in 1:10
           print(sin(k))
       end
0.84147098480789650.90929742682568170.1411200080598672-0.7568024953079282-0.9589242746631385-0.279415498198925860.65698659871878910.98935824662338180.4121184852417566-0.5440211108893698
julia> VERSION
v"1.7.2"
 
help?> @sprintf
  @sprintf("%Fmt", args...)

  Return @printf formatted output as string.

It returns a string, so:

julia> for k in 1:10
                println(   @sprintf("%.4f, ", sin(k)) )
              end
0.8415,
0.9093,
0.1411,
-0.7568,
-0.9589,
-0.2794,
0.6570,
0.9894,
0.4121,
-0.5440,
1 Like

Better to jut use @printf.

julia> for k in 1:10
           @printf("%.4f, ", sin(k))
       end
0.8415, 0.9093, 0.1411, -0.7568, -0.9589, -0.2794, 0.6570, 0.9894, 0.4121, -0.5440, 
2 Likes

Oh… so string is not printed automatically. I get it now

What you see printed in the REPL is the return value of your expression.
So if you build a structure that contains all the strings you will see it as well.
Printing on the other hand really produces output even if you are not running the program in the REPL.

Example in the REPL:

julia> using Printf

julia> map(1:3) do k
           println("hello!")
           @sprintf("%d",k)
       end
hello!
hello!
hello!
3-element Vector{String}:
 "1"
 "2"
 "3"

Same code without the REPL:

$ julia -e 'using Printf;map(1:3) do k;println("hello!");@sprintf("%d",k);end'
hello!
hello!
hello!
2 Likes