Encode/decode 使用 Python 2.7 十六进制表示法的字符串中的特定字符

Encode/decode specific character in string with hex notation using Python 2.7

如何对字符串 'banana' 进行编码,以便所有 a 都变成这样的 \x97?

b\x97n\x97n\x97

那么,如何将嵌入了十六进制值的字符串反转或解码回原始字符串 banana?

使用 str.replace 将该字符替换为其序数值的十六进制表示。要取回实际的字符串,您可以使用 string-decode.

对其进行解码
>>> s = 'banana'
>>> print s.replace('a', '\x' + format(ord('a'), 'x'))
b\x61n\x61n\x61
>>> print s.replace('a', '\x' + format(ord('a'), 'x')).decode('string-escape')
banana

这样做并保持编码为标准 ASCII 而不是十六进制...

import re
s = 'banana'
t = s.replace('a', '\x{}'.format(ord('a')))
subs = re.findall(r'\x\d{2}',t)
decoded = ""
for match in set(subs):
    decoded = t.replace(match, chr(int(match[2:4]))
print decoded