在python中将字母数字字符串转换为int,反之亦然

2024-04-29 03:34:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试将最大长度为40个字符的字母数字字符串转换为尽可能小的整数,以便我们可以轻松地从数据库中保存和检索。我不知道是否有任何python方法或者我们可以使用的任何简单算法。具体来说,我的字符串只有0-9和a-g两个字符,所以请帮助我们提供一些建议,说明如何从字符串唯一地转换为int,反之亦然。我在Cent os 6.5上使用Python 2.7


Tags: 方法字符串算法数据库os字母数字整数
3条回答

输入中有17个符号,因此可以将is视为基数17:

>>> int('aga0',17)
53924

对于反向转换,在here上有很多解。

对上述答案的改进:

# The location of a character in the string matters.
chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
charsLen = len(self.chars)

def numberToStr(num):
  s = ""
  while num:
    s = self.chars[num % charsLen] + s
    num //= charsLen

  return s # Or e.g. "s.zfill(10)"

可以处理前导0的字符串:

def strToNumber(numStr):
  num = 0
  for i, c in enumerate(reversed(numStr)):
    num += chars.index(c) * (charsLen ** i)

  return num

这并不难:

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

相关问题 更多 >