Search code examples
pythonnumpynumber-formatting

How to force at least N digits in Python (Numpy)


Let's say we have an arbitrary integer, x. I want to convert this number to a string; which is pretty easy using str(x).

Converting the number to a different base other than base 10 can be done easily in numpy using np.base_repr(x, base). But how do I force this to have at least N digits; if the number is 0 for example, base_repr will output just 0. But what if I want at least 5 digits, 00000?

I tried the padding setting in the np.base_repr function, but this seems to left-append extra zeroes, instead of adding them to fit. For example, np.base_repr(2, base=2, padding=3) yields 00010 instead of the desired 010.

I know this is possible manually. We can just append zeroes to our string (left-append) until the length is N. But is there a library function in numpy, or some other popular library, that does the trick?


Solution

  • Use f-string abilities or .zfill() string method for this:

    f"{2:03b}" # or:
    f"{2:b}".zfill(3)
    ## '010'
    

    b is for binary f would be for float :3 would enforce 3 positions, however, padding would be with . :03 enforces padding with zeros.

    f"{2:03}"
    ## '002'
    

    For different bases use:

    np.base_repr(2, base=2).zfill(3)
    

    or:

    f"{np.base_repr(2, base=3):03}"