Ì am able to convert any string
containing digits and valid characters (for that base) into an integer by specifying:
print ( int("ABCDEFGHIJKLMN", base=27) ) # for n in [0,2..36]
wich outputs 42246088999001073599
. int()
I am interested in the generic reverse of that. (up to 36 would be fine - same as int()
does)
Specialized solutions available I know of:
bin() # binary string representation - with prefix
oct() # octal string representation - with prefix
hex() # hexadecimal string representation - with prefix
str(num[, base=10] ) # for 0, 2..36
or you can use the mini format language to get the "pure" number string:
print(f"{32:o}") # ==> 40 = 4*8+2=32
Type Meaning 'b' Binary format. Outputs the number in base 2. 'o' Octal format. Outputs the number in base 8. 'x' Hex format. Outputs the number in base 16, using lower-case letters for the digits above 9. 'X' Hex format. Outputs the number in base 16, using upper-case letters for the digits above 9.
I do not know of any generalized int to string of base n
method.
I made one for base 12 in my answer to a base 12 question:
class Base12Convert: d = {hex(te)[2:].upper():te for te in range(0,12)} d.update({val:key for key,val in d.items()}) d["-"] = "-" # snipp: def text_to_int(text) @staticmethod def int_to_text(num): """Converts an int into a base-12 string.""" sign = "" if not isinstance(num,int): raise ValueError( f"Only integer as input allowed: '{num} of type {type(num)}' is invalid") if num < 0: sign = "-" num *= -1 # get highest possible number p = 1 while p < num: p *= 12 # create string rv = [sign] while True: p /= 12 div = num // p num -= div*p rv.append(Base12Convert.d[div]) if p == 1: break return ''.join(rv)
and could generalize that ... but I probably overlook a built in_one?