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

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

    This is an old question but I thought i'd share my take on it as I feel it is somewhat simpler that other answers (good for bases from 2 to 36):

    def intStr(n,base=10):
        if n < 0   : return "-" + intStr(-n,base)         # handle negatives
        if n < base: return chr([48,55][n>9] + n)         # 48 => "0"..., 65 => "A"...
        return intStr(n//base,base) + intStr(n%base,base) # recurse for multiple digits
    

提交回复
热议问题