[英]converting alphanumeric string to int and vice versa in python
我正在嘗試將最大長度為 40 個字符的字母數字字符串轉換為盡可能小的整數,以便我們可以輕松地從數據庫中保存和檢索。 我不知道是否有任何可用的 python 方法或我們可以使用的任何簡單算法。 具體來說,我的字符串將只有字符 0-9 和 ag。 因此,請就我們如何唯一地將字符串轉換為整數(反之亦然)提出任何建議。 我在 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 。
改進上述答案:
# The location of a character in the string matters.
chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
charsLen = len(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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.