将使用 Pickle 序列化的对象转换为 Python 中的字符串

Convert Object Serialized with Pickle to String in Python

如何将 pickle.dumps 的输出转换为字符串。我需要将输出转换为字符串。

当前,这是我得到的:

import pickle

class TestClass:
    def __init__(self, number):
        self.number = number

t1 = TestClass(14)
s1 = pickle.dumps(t1)
str_version = s1.decode('utf-8', 'backslashreplace')
print(pickle.loads(str_version.encode('utf-8', 'backslashreplace')))

但我收到错误消息:

Traceback (most recent call last):
  File "C:\Users\ketha\Downloads\python_testing.py", line 11, in <module>
    print(pickle.loads(str_version.encode('utf-8', 'backslashreplace')))
_pickle.UnpicklingError: invalid load key, '\x5c'.

我认为这是因为当我将它转换为字符串时,它会将 \x5c(例如)转换为 \x5c,并且在解码期间不会撤消此操作。我该如何撤消此操作?

我得到了一些代码。代码:

import pickle
import sys

class TestClass:
    def __init__(self, number):
        self.number = number

t1 = TestClass(14)
s1 = pickle.dumps(t1)
str_version = s1.decode('unicode_escape')
decoded = pickle.loads(str_version.encode('utf-8', 'unicode_escape').replace(b'\xc2', b''))
print(decoded.number)