我有许多Python字节对象存储在文本文件中,Python以
"b'\x80\x03}q\x00.'"
的形式打印。如何将它们转换回字节对象? 换句话说,我试图找到一个函数,使得 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
bytes
字面值的字符串表示,而不是bytes
对象。这个文件最初是如何创建的? - chepnerbytes
字面量。对于s =“...”
,例如\x00
会被替换为实际的空字节,而不是保留表示空字节的4个字符的字面值。如果你写s = r"..."
,那么ast.literal_eval(s)
将返回你想要的bytes
对象。 - chepners
;如果s
是从文件中读取的,例如s = f.readline()
,那么这就不是一个问题。 - chepnerbytes(s[2:-1].encode())[1:] # b'\x80\x03}q\x00.'
- Darkonautbyte-string
转换为string
!最好的方法是进行解码。例如:bs = b'\x80\x03}q\x00.'
,然后你应该写成s = bs.decode()
,这样你就可以随时使用s.encode()
将其转换回 byte-string :) - Hamidreza