如何将Python字节字符串表示形式转换为字节?

Cer*_*rin 3 python

我有许多 Python 字节对象存储在一个文本文件中,Python 会打印"b'\x80\x03}q\x00.'"这些对象,例如 How do I conversion back into a bytes object?

换句话说,我正在尝试找到一个可以实现的功能convert("b'\x80\x03}q\x00.'") == b'\x80\x03}q\x00.'

我觉得这应该是微不足道的,但这些明显的方法都不起作用:

>>> s = "b'\x80\x03}q\x00.'"
>>> bytes(s)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: string argument without an encoding
>>> bytes(s.encode())
b"b'\xc2\x80\x03}q\x00.'"
>>> bytes(s[2:-1].encode())
b'\xc2\x80\x03}q\x00.'
>>> bytes(s[2:-1].encode('utf8'))
b'\xc2\x80\x03}q\x00.'
>>> eval(s)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: source code string cannot contain null bytes
>>> exec(s)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: source code string cannot contain null bytes
Run Code Online (Sandbox Code Playgroud)

che*_*ner 5

s这并不真正适用于从文件读取 的值的情况,但在您的示例中,常规字符串文字扩展了转义序列:

>>> s = "b'\x80\x03}q\x00.'"
>>> list(s)
['b', "'", '\x80', '\x03', '}', 'q', '\x00', '.', "'"]
Run Code Online (Sandbox Code Playgroud)

请注意,s不包含空字节的转义序列;它包含一个实际的空字节。

您可以使用原始字符串文字来避免这种情况:

>>> s = r"b'\x80\x03}q\x00.'"
>>> list(s)
['b', "'", '\\', 'x', '8', '0', '\\', 'x', '0', '3', '}', 'q', '\\', 'x', '0', '0', '.', "'"]
Run Code Online (Sandbox Code Playgroud)

在这种情况下,ast.literal_eval您正在寻找的功能是:

>>> ast.literal_eval(s)
b'\x80\x03}q\x00.'
Run Code Online (Sandbox Code Playgroud)

原始字符串文字应该生成您从文件中读取的值:

import ast

b = b'\x80\x03}q\x00.'

with open("tmp.txt", "w") as f:
    print(str(b), file=f)

with open("tmp.txt") as f:
    s = f.readline().strip()

assert ast.literal_eval(s) == b
Run Code Online (Sandbox Code Playgroud)