Search code examples
stringjulialeading-zero

Number to string with leading (left padded) zeros in Julialang


It seems as an easy question, but I cannot find the answer anywhere. If I have an integer variable, how can I transform it to a string with leading zeros?

I want something as the code below:

n = 4
string_size = 3
println(fleading(n, string_size)) 
# result should be "004"

Where fleading would be something like the function to transform the number to string with leading zeros. The analogous way in python is str(4).zfill(3) which gives 004 as result.


Solution

  • You're looking for the lpad() (for left pad) function:

    julia> lpad(4,3,"0")
    "004"
    

    Note the last argument must be a string.

    From the documentation:

    lpad(string, n, "p")

    Make a string at least n columns wide when printed, by padding on the left with copies of p.