Convert int to ASCII and back in Python

前端 未结 5 2105
庸人自扰
庸人自扰 2020-12-04 06:08

I\'m working on making a URL shortener for my site, and my current plan (I\'m open to suggestions) is to use a node ID to generate the shortened URL. So, in theory, node 26

5条回答
  •  旧巷少年郎
    2020-12-04 06:24

    Use hex(id)[2:] and int(urlpart, 16). There are other options. base32 encoding your id could work as well, but I don't know that there's any library that does base32 encoding built into Python.

    Apparently a base32 encoder was introduced in Python 2.4 with the base64 module. You might try using b32encode and b32decode. You should give True for both the casefold and map01 options to b32decode in case people write down your shortened URLs.

    Actually, I take that back. I still think base32 encoding is a good idea, but that module is not useful for the case of URL shortening. You could look at the implementation in the module and make your own for this specific case. :-)

提交回复
热议问题