ASCII 到整数:
ord('a')
给出97
回到一个字符串:
在 Python2 中:str(unichr(97))
在 Python3 中:chr(97)
给出'a'
>>> ord("a")
97
>>> chr(97)
'a'
如果多个字符绑定在一个整数/长整数内,我的问题是:
s = '0123456789'
nchars = len(s)
# string to int or long. Type depends on nchars
x = sum(ord(s[byte])<<8*(nchars-byte-1) for byte in range(nchars))
# int or long to string
''.join(chr((x>>8*(nchars-byte-1))&0xFF) for byte in range(nchars))
产生 '0123456789'
和 x = 227581098929683594426425L
BASE58 编码 URL 怎么样?就像 flickr 一样。
# note the missing lowercase L and the zero etc.
BASE58 = '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'
url = ''
while node_id >= 58:
div, mod = divmod(node_id, 58)
url = BASE58[mod] + url
node_id = int(div)
return 'http://short.com/%s' % BASE58[node_id] + url
把它变成一个数字也没什么大不了的。
使用 hex(id)[2:]
和 int(urlpart, 16)
。还有其他选择。 base32 编码你的 id 也可以工作,但我不知道有任何库可以在 Python 中内置 base32 编码。
显然,在 Python 2.4 中使用 base64 module 引入了 base32 编码器。您可以尝试使用 b32encode
和 b32decode
。您应该为 b32decode
提供 casefold
和 map01
选项的 True
,以防人们记下您缩短的 URL。
实际上,我收回了这一点。我仍然认为 base32 编码是一个好主意,但是该模块对于 URL 缩短的情况没有用。您可以查看模块中的实现并为这种特定情况制作自己的实现。 :-)
不定期副业成功案例分享