How to convert an integer to a string in any base?

前端 未结 27 3167
清歌不尽
清歌不尽 2020-11-22 02:25

Python allows easy creation of an integer from a string of a given base via

int(str, base). 

I want to perform the inverse: creati

27条回答
  •  梦谈多话
    2020-11-22 02:55

    Here is a recursive version that handles signed integers and custom digits.

    import string
    
    def base_convert(x, base, digits=None):
        """Convert integer `x` from base 10 to base `base` using `digits` characters as digits.
        If `digits` is omitted, it will use decimal digits + lowercase letters + uppercase letters.
        """
        digits = digits or (string.digits + string.ascii_letters)
        assert 2 <= base <= len(digits), "Unsupported base: {}".format(base)
        if x == 0:
            return digits[0]
        sign = '-' if x < 0 else ''
        x = abs(x)
        first_digits = base_convert(x // base, base, digits).lstrip(digits[0])
        return sign + first_digits + digits[x % base]
    

提交回复
热议问题