代码之家  ›  专栏  ›  技术社区  ›  mlissner

将int转换为ASCII并返回Python

  •  110
  • mlissner  · 技术社区  · 14 年前

    我正在为我的网站制作一个URL缩短器,我目前的计划(我愿意接受建议)是使用一个节点ID来生成缩短的URL。所以,理论上,节点26可能是 short.com/z short.com/a ,节点52可能是 short.com/Z short.com/ZZ . 当用户访问该URL时,我需要反转这个过程(显然)。

    我可以想出一些愚蠢的方法来解决这个问题,但我想还有更好的方法。有什么建议吗?

    5 回复  |  直到 9 年前
        1
  •  239
  •   Mike T    4 年前

    ASCII到int:

    ord('a')
    

    给予 97

    回到一根绳子上:

    • str(unichr(97))
    • 在蟒蛇3中: chr(97)

    'a'

        2
  •  98
  •   renatov    9 年前
    >>> ord("a")
    97
    >>> chr(97)
    'a'
    
        3
  •  9
  •   Matthew Davis    8 年前

    如果在一个整数/长整型内绑定了多个字符,我的问题是:

    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

        4
  •  7
  •   Ivo Wetzel    14 年前

    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
    

    把它变成一个数字也没什么大不了的。

        5
  •  0
  •   tiger li    4 年前

    将ord()用于ASCII-->int

    将chr()用于int-->ASCII

        6
  •  -1
  •   Omnifarious    14 年前

    使用 hex(id)[2:] int(urlpart, 16) . 还有其他选择。base32编码您的id也可以工作,但我不知道在Python中是否有任何库可以进行base32编码。

    显然,在python2.4中引入了base32编码器 base64 module . 你可以试着用 b32encode b32decode . 你应该付出 True casefold map01 选择 代码B32 以防人们写下你缩短的网址。