How to create a file where the columns are separated by equal space

Here is the code I use to create the file:

ar = [[1, 85645, 197111, 197240], [1, 203753],[1, 24]]                  

loop = 0
for i =1:3#length(ar)
    val = ar[i]' .-1
    print(ff, "NetDegree : ", length(val), "   ", "n", loop)
    print(ff, '\n')
    for jj = 1:length(val)
        vv = val[jj]
        print(ff, "\t", "o", val[jj], " I : ", 5.000000, " ", -5.000000)
        print(ff, "\n")
    end #end of jj

    loop +=1

end # end of for i

end

The output is:

Screen Shot 2020-09-08 at 1.23.35 AM

but I need it to be like the following:
Screen Shot 2020-09-08 at 1.25.20 AM

Please ignore the mismatch between the numbers. My question is how to make each line with the same format.

If you know the maximum width, you can pad using @printf, see

https://docs.julialang.org/en/v1/stdlib/Printf/

Otherwise, you can convert the fields with string in one pass and get the maximum width, then print padding to that in a second pass. See eg lpad.

2 Likes

(also, moving this to Usage from Performance)

Yes, as @Tamas_Papp said, @printf is quite easy to use for this:

using Printf
ar = [[1, 85645, 197111, 197240], [1, 203753],[1, 24]]                  

loop = 0
for i =1:length(ar)
    val = ar[i]' .-1
    @printf("NetDegree : %-2d n%d ", length(val), loop)
    @printf("\n")
    for jj = 1:length(val)
        vv = val[jj]
        @printf("\t\t o%-6d  I : %9.6f, %9.6f", val[jj], 5.000000, -5.000000)
        @printf("\n")
    end # end of jj
    loop += 1
end # end of i

Output:

NetDegree : 4  n0 
         o0       I :  5.000000, -5.000000
         o85644   I :  5.000000, -5.000000
         o197110  I :  5.000000, -5.000000
         o197239  I :  5.000000, -5.000000
NetDegree : 2  n1 
         o0       I :  5.000000, -5.000000
         o203752  I :  5.000000, -5.000000
NetDegree : 2  n2 
         o0       I :  5.000000, -5.000000
         o23      I :  5.000000, -5.000000
2 Likes

Can you also help me to write this into a file. I tried this:

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)

This works but it doesn’t generate the tab space at the beginning and writes “\t” instead. I don’t know why using @printf instead of @sprintf doesn’t work at all.