Python elegant inverse function of int(string,base)

后端 未结 11 852
谎友^
谎友^ 2020-11-28 06:01

python allows conversions from string to integer using any base in the range [2,36] using:

int(string,base)

im looking for an elegant inver

11条回答
  •  [愿得一人]
    2020-11-28 06:27

    numpy.base_repr is a quite good solution, however, in some cases, we want a fixed-length string with leading zeros.

    def base_repr(x: int, base: int, length: int):
        from numpy import base_repr
        from math import log, ceil
        s = base_repr(x, base, length - ceil(log(x, base)))
        return s
    

提交回复
热议问题