Search code examples
pythonnumpyradix

Is there an easy way to implement width for `numpy.base_repr`?


The numpy.binary_reps has the nice 'width' keyword to set the desired width of the output. The numpy.base_repr function does instead have the weird choice 'padding' as a keyword.

Thus if i want to have a specific WIDTH of my base N output, instead of

np.base_repr(x,base=N,width=WIDTH)

i need to do

np.base_repr(x,base=N,padding=WIDTH-int(np.ceil(np.log(x+1)/np.log(N)))

which is sub-optimal to say the least. Does anybody know of a way around this?


Solution

  • If you're messing with strings anyway, just do it after?

    res = np.base_repr(x, base=N)
    res = '0' * (WIDTH - len(res)) + res