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

前端 未结 27 3101
清歌不尽
清歌不尽 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:54

    >>> import string
    >>> def int2base(integer, base):
            if not integer: return '0'
            sign = 1 if integer > 0 else -1
            alphanum = string.digits + string.ascii_lowercase
            nums = alphanum[:base]
            res = ''
            integer *= sign
            while integer:
                    integer, mod = divmod(integer, base)
                    res += nums[mod]
            return ('' if sign == 1 else '-') + res[::-1]
    
    
    >>> int2base(-15645, 23)
    '-16d5'
    >>> int2base(213, 21)
    'a3'
    

提交回复
热议问题