logo

How to Use zfill() in Julia 📂Julia

How to Use zfill() in Julia

Overview 1

In Python, zfill() actually serves as a method of the string class, filling the left side with zeros. Julia, on the other hand, offers the lpad() as a more versatile and widely applicable built-in function. While zfill() means to fill with zeros, lpad() signifies padding to the left.

Code

julia> lpad("12", 4, "0")
"0012"

julia> lpad(12, 4, "0")
"0012"

Continuing from the overview, lpad() in Julia is more generic compared to zfill(). It’s not a method of the string, so it returns a string whether the argument is a string or a number.

julia> lpad(12, 4)
"  12"

julia> lpad(12, 4, "_")
"__12"

julia> lpad(12, 4, "_!")
"_!12"

julia> lpad(12, 4, "_?!")
"_?12"

julia> lpad(12, 7, "_?!")
"_?!_?12"

The common reason for using such a function is to tidy up the output aligning spaces, not necessarily because zeros are needed. If no filling character is provided, it uses a space, and if a character or string is given, it intelligently fills it as seen above.

julia> rpad("left", 6, '0')
"left00"

Of course, there’s also the rpad() function. It has the same basic functionality, only differing in that it pads to the right.

Environment

  • OS: Windows
  • julia: v1.6.0