Expose possibility to format ints in all supported bases?

Despite int constructor accepts strings in any base in range(2, 37), currently we can format numbers only in decimal, binary, octal or hexadecimal. (str, repr, bin, oct, hex and format builtins, respectively.)

Occasionally, for debugging and/or interoperation it’s useful to print numbers in other bases. Unfortunately, we don’t have a method for this: users have to reinvent the wheel here.

Such support was requested before in new-style string formatting. Though, this introduce complications in the string formatting mini-language for rather niche case. How about simpler API, just a new method for int’s?

All (direct or indirect) Python interfaces to the GNU GMP have such methods. The gmpy2 and python-gmp packages have digits() method. The python-flint has str() method, similar to Sagemath’s str(). An example:

>>> import flint
>>> n = flint.fmpz.fac_ui(50)
>>> n.str(base=32)
'ifenib1tkjpm0lhtt7ihkcqgjqpeegt5hs000000000'

I propose this method for integer objects:

def digits(self, /, base=10):
    """
    Return string representing self in the given base.

    Values for base can range between 2 to 36.
    """
    ...

On the C-API side we could relax requirements on the base argument for PyNumber_ToBase() functions (currently accepting 2, 8, 10 and 16).

Note, that all stuff is already implemented (and probably much better than a homegrown code snippet from a random “inventor”) in the CPython (e.g. _PyLong_Format() private function) and in alternative interpreters I know.

3 Likes