0

我有一个字符串,"stringify". 正在做:

int("stringify",36)

返回:

81323539083358

有没有办法将该数字转换回“字符串化”?

4

2 回答 2

2

没有内置方法将此数字编码回基数 36,但 Wikipedia 上有一个 Python 实现:
http ://en.wikipedia.org/wiki/Base_36#Python_implementation

这是该代码的略微修改版本(只是将大写字母更改为小写):

def base36encode(number, alphabet='0123456789abcdefghijklmnopqrstuvwxyz'):
    """Converts an integer to a base36 string."""
    if not isinstance(number, (int, long)):
        raise TypeError('number must be an integer')

    base36 = ''
    sign = ''

    if number < 0:
        sign = '-'
        number = -number

    if 0 <= number < len(alphabet):
        return sign + alphabet[number]

    while number != 0:
        number, i = divmod(number, len(alphabet))
        base36 = alphabet[i] + base36

    return sign + base36

>>> base36encode(81323539083358)
'stringify'
于 2013-10-18T16:19:12.163 回答
1

只是为了好玩,它是一个编解码器

import codecs
class SimpleB36Encoder:
    def encode(self,txt,errors=[]):
        return str(int(txt,36)),1

    def decode(self,txt,errors=[]):
        number = int(txt)
        alphabet = "0123456789abcdefghijklmnopqrstuvwxyz"
        base36 = ''
        sign = ''
        if number < 0:
            sign = '-'
            number = -number
        if 0 <= number < len(alphabet):
            return sign + alphabet[number]
        while number != 0:
            number, i = divmod(number, len(alphabet))
            base36 = alphabet[i] + base36
        return sign + base36,1


def find_b36(search=""):
    if search.lower() in ["base36","b36","36"]:
        return codecs.CodecInfo(
            name='base36',
            encode=SimpleB36Encoder().encode,
            decode=SimpleB36Encoder().decode
            )

codecs.register(find_b36)
encoded = "stringify".encode("36") #note this is a string
print "stringify encodes to %s"%encoded
decoded = encoded.decode("36")
print "%s decodes to %s"%(encoded,decoded)
于 2013-10-18T16:42:18.907 回答