Python-字符串到字节的转换。双反斜杠问题

Python-String to Bytes conversion. Double BackSlash issue

我有问题。我有这个字符串:

a=O\x8c\x90\x05\xa1\xe2!\xbe

如果我使用:

c=str.encode(a)

这是结果:

b'O\x8c\x90\x05\xa1\xe2!\xbe'

我需要那些双反斜杠是单反斜杠,我真的需要那种类型的数据是 BYTES。我需要 return 这个:

c=b'0\x8c\x90\x05\xa1\xe2!\xbe'

然后输入(c)==bytes 有什么想法吗?

您可以使用 str.decode() 编码为 unicode-escape 。然后使用所需的编码将其解码回来以取回您的字节数组。例子-

c = a.decode('unicode-escape').encode('<required encoding>')

演示 -

>>> a
b'O\x8c\x90\x05\xa1\xe2!\xbe'
>>> c = a.decode('unicode-escape').encode('ISO-8859-1')
>>> c
b'O\x8c\x90\x05\xa1\xe2!\xbe'