解码字节而不会丢失数据

输入是一个字节变量,其值为b'\x1f\x8b\x08\x00',需要将其转换为字符串。 预期输出为'\x1f\x8b\x08\x00'

我该如何实现?

我正在使用zlib来获取输入的gzip数据,并且需要解压缩为浏览器的字符串。

我尝试添加errors='ignore'参数。

我尝试提供“ latin1”编码,但浏览器无法解压缩数据。

>>> a = b'\x1f\x8b\x08\x00'
>>> z = a.decode('utf-8')
Traceback (most recent call last):
  File "<stdin>",line 1,in <module>
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x8b in position 1: invalid start byte
>>> z = a.decode('utf-8',errors = 'ignore')
>>> z
'\x1f\x08\x00'

预期结果'\x1f\x8b\x08\x00'

sunvisual 回答:解码字节而不会丢失数据

您可以转换字符串并去除不需要的字符:

z = b'\x1f\x8b\x08\x00'
a = str(z)[2:-1]
print(a)
print(type(a))

输出:

\x1f\x8b\x08\x00
<class 'str'>

在Python3.7中的用法:

Python 3.7.4 (default,Aug 17 2019,13:54:58)
[Clang 10.0.1 (clang-1001.0.46.4)] on darwin
Type "help","copyright","credits" or "license" for more information.
>>> a = b'\x1f\x8b\x08\x00'
>>> b = str(a)[2:-1]
>>> b
'\\x1f\\x8b\\x08\\x00'
>>> print(b)
\x1f\x8b\x08\x00
>>>
本文链接:https://www.f2er.com/3123767.html

大家都在问