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

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

    Another short one (and easier to understand imo):

    def int_to_str(n, b, symbols='0123456789abcdefghijklmnopqrstuvwxyz'):
        return (int_to_str(n/b, b, symbols) if n >= b else "") + symbols[n%b]
    

    And with proper exception handling:

    def int_to_str(n, b, symbols='0123456789abcdefghijklmnopqrstuvwxyz'):
        try:
            return (int_to_str(n/b, b) if n >= b else "") + symbols[n%b]
        except IndexError:
            raise ValueError(
                "The symbols provided are not enough to represent this number in "
                "this base")
    

提交回复
热议问题