Python elegant inverse function of int(string,base)

后端 未结 11 872
谎友^
谎友^ 2020-11-28 06:01

python allows conversions from string to integer using any base in the range [2,36] using:

int(string,base)

im looking for an elegant inver

11条回答
  •  生来不讨喜
    2020-11-28 06:13

    The above answers are really nice. It helped me a lot to prototype an algortithm I had to implement in C

    I'd like to come up with a little change (I used) to convert decimal to a base of symbolspace

    I also ignored negativ values just for shortness and the fact that's mathematical incorrect --> other rules for modular arithmetics --> other math if you use binary, oct or hex --> diff in unsigned & signed values

    def str_base(number, base):
       (d,m) = divmod(number,len(base))
       if d > 0:
          return str_base(d,base)+base[m]
       return base[m]
    

    that lead's to following output

    >>> str_base(13,'01')
    '1101'
    >>> str_base(255,'01')
    '11111111'
    >>> str_base(255,'01234567')
    '377'
    >>> str_base(255,'0123456789')
    '255'
    >>> str_base(255,'0123456789abcdef')
    'ff'
    >>> str_base(1399871903,'_helowrd')
    'hello_world'
    

    if you want to padd with the propper zero symbol you can use

    symbol_space = 'abcdest'
    
    >>> str_base(734,symbol_space).rjust(0,symbol_space[0])
    'catt'
    >>> str_base(734,symbol_space).rjust(6,symbol_space[0])
    'aacatt'
    

提交回复
热议问题