How to create tab space using @sprintf?

For some reasons, I would like to stick to using sprintf and I need to write into a file when each line has a tab space in the beginning. Here is what I wrote but it doesn’t work:

ff = open("test.txt", "w")

ss = Array{String, 0}

ss = @sprintf("\t o%-6d  I : %9.6f, %9.6f", val[jj], 5.000000, -5.000000)

print(ff, ss)

instead of creating the space, it just writes “\t” into the file.

Why writing to an array of strings? You can write directly to the file:

julia> open("test.txt", "w") do io
           for i in 1:5
               @printf(io, "\t o%-6d  I : %9.6f, %9.6f\n", i, rand(), -rand())
           end
       end

shell> cat test.txt
         o1       I :  0.499033, -0.518227
         o2       I :  0.452359, -0.057112
         o3       I :  0.137529, -0.954224
         o4       I :  0.792647, -0.996261
         o5       I :  0.859669, -0.768580

This actually works. Thank you.

BTW, I can’t reproduce the problem you were saying:

julia> ff = open("test.txt", "w")
IOStream(<file test.txt>)

julia> ss = @sprintf("\t o%-6d  I : %9.6f, %9.6f", 10, 5.000000, -5.000000)
"\t o10      I :  5.000000, -5.000000"

julia> print(ff, ss)

julia> close(ff)

shell> cat test.txt
         o10      I :  5.000000, -5.000000

This is what I get:

@sprintf("\t o%-6d %s :%9.6f %9.6f", val[jj], SS, 5.000000, -5.000000)
"\t o197239 I : 5.000000 -5.000000"

My Julia version is 1.2.0

Well, that’s normal: you write out a string which contains a literal \t, but when you print it the \t is interpreted as a tab:

julia> ss = "\t o197239 I : 5.000000 -5.000000"
"\t o197239 I : 5.000000 -5.000000"

julia> println(ss)
         o197239 I : 5.000000 -5.000000
2 Likes

Got it. Thank you.