python2 unicode str

这个问题到python3里面就没了,python3 似乎将这个无形中解决了。


 错误信息:

utf8 codec can't decode byte 0xb5 in position
有汉字
抓取网页的时候,网页可能有两种编码(utf-8  + GBK23)
编码有中文 也有英文


html的编码是ANSI的,另存为UTF-8即可。

错误信息
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe5 in position 108: ordinal not in range(128)  
混淆了 python2 里边的 str 和 unicode 数据类型。 
0. 
你需要的是让编码用实际编码而不是 ascii 
1. 
对需要 str->unicode 的代码,可以在前边写上 
import sys 
reload(sys) 
sys.setdefaultencoding('utf8') 
把 str 编码由 ascii 改为 utf8 (或 gb18030) 
2. 
python3 区分了 unicode str 和 byte arrary,并且默认编码不再是 ascii 
You use u"你好".encode('utf8') to encode an unicode string. But if you want to represent "你好", you should decode it. Just like:
"你好".decode("utf8")
encode converts a unicode object to a string object. But here you have invoked it on a string object (because you don't have the u). So python has to convert the string to a unicode object first. So it does the equivalent of"你好".decode().encode('utf-8')

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值