python requests编码的问题_Requests 库编码问题及引出的 Python 编码问题

Requests 编码

在使用 requests 访问微信接口的时候,requests 只根据 http headers 的信息来设置编码集,文档如下:

response.text()

Content of the response, in unicode.

If Response.encoding is None, encoding will be guessed using chardet.

The encoding of the response content is determined based solely on HTTP headers, following RFC 2616 to the letter. If you can take advantage of non-HTTP knowledge to make a better guess at the encoding, you should set r.encoding appropriately before accessing this property.

这边就是说,我们的选择还有,当服务器不指定编码集时,使用以下方式指定编码,然后再将 text 输出,输出的为 unicode。

r.encoding = 'utf-8'

r.text

关于这个的话题的讨论可以看这里。

当我们使用urllib2.urlopen('http://www.baidu.com').read()时,返回的则是 str 格式。

Python 2 编码问题

# Python 2 默认赋值时为字节串即 str 类型,此处的哈哈经过 utf-8 编码以后变成了 \xe5\x93\x88\xe5\x93\x88,此时 len(x) == 6

>>> x="哈哈"

>>> x

'\xe5\x93\x88\xe5\x93\x88'

>>> type(x)

# 由于储存哈哈到 str 类型时经过了 utf-8 编码,所以要想获得哈哈,就必须通过解码,解码后得到 unicode 类型的字符串

>>> x.decode('utf-8')

u'\u54c8\u54c8'

# 呵呵在储存的时候 u 指定了它是 unicode 类型,所以变量 y 是真正意义上的字符串,我们可以通过 encode 操作将它转换为 str 类型

>>> y=u"呵呵"

>>> y

u'\u5475\u5475'

>>> type(y)

>>> y.encode('utf-8')

'\xe5\x91\xb5\xe5\x91\xb5'

>>> type(y.encode('utf-8'))

Python 3 编码问题

>>> x='哈哈'

# Python 3 中的 str 类型储存的其实是 Python 2 中的 unicode 字符串,即是真正意义上的字符串

>>> type(x)

# 通过 Python 2 一样的方法,我们可以将一个 unicode 转换为一个 bytes 字节串,这里 bytes 其实就是 Python 2 中的 str 类型。

>>> y = x.encode('utf=8')

>>> y

b'\xe5\x93\x88\xe5\x93\x88'

>>> type(y)

>>>

总结

Python 2 中 str 和 Python 3 中 bytes 是一个东西

Python 2 中 unicode 和 Python 3 中 str 是一个东西

字符串编码后得到字节串,字节串解码后得到字符串

打开文件使用 codecs.open() 可以指定编码格式

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值