python中是否有通用的“ str(int,base = n)”功能?

时间:2018-12-14 12:07:32

标签: python string python-3.x int base

Ì能够通过指定以下内容将包含位数字和有效字符(针对该基数)的任何string转换为整数。

print ( int("ABCDEFGHIJKLMN", base=27) ) # for n in [0,2..36]

将输出42246088999001073599输出。 int()

我对它的通用反向感兴趣。(最多可以有36个-与int()相同)


我知道的

专业解决方案

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

或者您可以使用mini format language来获取“纯”数字字符串:

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.

我不知道任何广义的 int to string of base n 方法。


我在my answer to a base 12 question中以12为底得分了:

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)

并且可以概括一下……但是我可能忽略了内置的in_one?

0 个答案:

没有答案