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

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

    Recursive

    I would simplify the most voted answer to:

    BS="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    def to_base(n, b): 
        return "0" if not n else to_base(n//b, b).lstrip("0") + BS[n%b]
    

    With the same advice for RuntimeError: maximum recursion depth exceeded in cmp on very large integers and negative numbers. (You could usesys.setrecursionlimit(new_limit))

    Iterative

    To avoid recursion problems:

    BS="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    def to_base(s, b):
        res = ""
        while s:
            res+=BS[s%b]
            s//= b
        return res[::-1] or "0"
    

提交回复
热议问题