Python将非数字字符串存储为数字

Sjo*_*elt 1 python

我目前正在尝试找到一种将任何类型的文本转换为数字的方法,以便以后可以将其转换回文本。所以像这样:

text = "some string"
number = somefunction(text)

text = someotherfunction(number)
print(text) #output "some string"
Run Code Online (Sandbox Code Playgroud)

Sha*_*ger 5

如果您使用的是 Python 3,则非常简单。首先,转换strbytes在选定的编码(utf-8通常是合适的),然后使用int.from_bytes要转换为int

number = int.from_bytes(mystring.encode('utf-8'), 'little')
Run Code Online (Sandbox Code Playgroud)

转换回来有点棘手(并且会丢失尾随NUL字节,除非您已将结果字符串存储在其他地方的长度;如果切换到'big'字节序,则会丢失前导NUL字节而不是尾随字节):

recoveredstring = number.to_bytes((number.bit_length() + 7) // 8, 'little').decode('utf-8')
Run Code Online (Sandbox Code Playgroud)

您可以在 Python 2 中做类似的事情,但效率较低/直接:

import binascii
number = int(binascii.hexlify(mystring.encode('utf-8')), 16)

hx = '%x' % number
hx = hx.zfill(len(hx) + (len(hx) & 1))  # Make even length hex nibbles
recoveredstring = binascii.unhexlify(hx).decode('utf-8')
Run Code Online (Sandbox Code Playgroud)

这相当于'big'Python 3 中的endian 方法;在每个方向上颠倒中间字节会得到'little'效果。