我正在尝试将最大长度为 40 个字符的字母数字字符串转换为尽可能小的整数,以便我们可以轻松地从数据库中保存和检索。我不知道是否存在任何 python 方法或我们可以使用的任何简单算法。具体来说,我的字符串将只有字符 0-9 和 a-g。因此,请提供有关我们如何从字符串唯一地转换为 int 以及反之亦然的任何建议。我在 Cent os 6.5 上使用 Python 2.7
最佳答案
这并不难:
def str2int(s, chars):
i = 0
for c in reversed(s):
i *= len(chars)
i += chars.index(c)
return i
def int2str(i, chars):
s = ""
while i:
s += chars[i % len(chars)]
i //= len(chars)
return s
例子:
>>> chars = "".join(str(n) for n in range(10)) + "abcdefg"
>>> str2int("0235abg02", chars)
14354195089
>>> int2str(_, chars)
'0235abg02'
基本上,如果您想将 n 个字符编码为一个整数,您可以将其解释为 base-n。
关于python - 在python中将字母数字字符串转换为int,反之亦然,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29026687/