0
我有一個字符串,"stringify"
。這樣做的:瞭解pythons int方法
int("stringify",36)
回報:
81323539083358
有沒有一種辦法,這個數字轉換回 「字符串」?
我有一個字符串,"stringify"
。這樣做的:瞭解pythons int方法
int("stringify",36)
回報:
81323539083358
有沒有一種辦法,這個數字轉換回 「字符串」?
沒有這個數字編碼回基地36內置的方式,但對維基百科的一個Python實現:
http://en.wikipedia.org/wiki/Base_36#Python_implementation
這裏是代碼稍加修改的版本(只是改變了大寫字母爲小寫):
def base36encode(number, alphabet='abcdefghijklmnopqrstuvwxyz'):
"""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'
只是爲了好玩在這裏是作爲一個編解碼器
import codecs
class SimpleB36Encoder:
def encode(self,txt,errors=[]):
return str(int(txt,36)),1
def decode(self,txt,errors=[]):
number = int(txt)
alphabet = "abcdefghijklmnopqrstuvwxyz"
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)
呸你打我,我是WRI在我的控制檯中做類似的事情 –