将python字节类型更改为字符串 [英] Change python byte type to string
问题描述
我正在使用 python 来玩 stackoverflow API.我运行以下命令:
I'm using python to play with the stackoverflow API. I run the following commands:
f = urllib.request.urlopen('http://api.stackoverflow.com/1.0/stats')
d = f.read()
d 的类型是字节"类,如果我打印它,它看起来像:
The type of d is class 'bytes' and if I print it it looks like:
b'\x1f\x8b\x08\x00\x00\x00 .... etc
我尝试了 d=f.read().decode('utf-8')
因为这是标题中指示的字符集,但我得到了'utf8' 编解码器无法解码位置 1 中的字节 0x8b"
错误消息
I tried d=f.read().decode('utf-8')
as that is the charset indicated in the header, but I get a
'utf8' codec can't decode byte 0x8b in position 1"
error message
如何将我从 urllib.request 调用中收到的字节对象转换为字符串?
How do I convert the byte object I received from my urllib.request call to a string?
推荐答案
检查以确保您的响应正文没有被压缩.相信它的传输编码或响应头的此类编码,我非常有信心您处理压缩数据而不是字符集编码问题.
Check to make sure your response body is not gzipped. Believe its transfer encoding or such for the response header, i have a high confidence that your dealing with compressed data and not character set encoding issues.
更新:意识到我有一个不解释/提供足够细节的坏习惯.对于 Python gzip'd 字节字符串,它们总是以 1f8b 开头 有人在这里解释得更好 https://stackoverflow.com/a/3703300/9908
update: Realizing I have a bad habit of not explaining/providing enough detail. For Python gzip'd byte strings they always start with 1f8b Someone explains it better here https://stackoverflow.com/a/3703300/9908
这篇关于将python字节类型更改为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!