我有一个字符串"stringify"
。这样做的:
int("stringify",36)
返回:
81323539083358
有没有办法将该号码转换回“stringify”?
答案 0 :(得分:2)
没有内置的方法将此数字编码回基数36,但维基百科上有一个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'
答案 1 :(得分: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)