'ascii' codec can't decode byte 0x** in position **, ordinal not in range(128)

今天在写Python时遇到程序报错,内容如题所示
在网上搜索了资料之后发现应该是编码的错误
检查了代码之后发现有一段:

updatedsummary = self._generate_summary(repo, parent, rev)
for line in oldsummary.splitlines()[4:]:
    if not re.match('\| \d+ \| \w+ \| \w+ \|.+', line):
        updatedsummary += '%s\n' % line
return updatedsummary

其中updatesummary是由函数self._generate_summary返回的,查看类型发现它是Unicode的对象,而oldsummary是从网页中读取回来的,其中有包含中文,而我又在oldsummary产生的时候将其编码成了utf-8格式,所以line都是utf-8编码的str类型。

因此在执行updatedsummary += '%s\n' % line时,Python会自动将str类型解码成unicode,Python预设的解码器是ascii,所以解码中文str时就会跳出如题的bug。

可以写一个脚本验证一下:

a = 'Hello'
b = '你好'
c = u'Hello'
print a + b  # '\xe4\xbd\xa0\xe5\xa5\xbdHello'
print a + c  # u'HelloHello'
#print b + c  # UnicodeDecodeError: 'ascii' codec can't decode byte 0xe4 in position 0: ordinal not in range(128)

因此解决这个问题只需我们手动将str解码就可以了,将代码改成:

updatedsummary = self._generate_summary(repo, parent, rev)
for line in oldsummary.splitlines()[4:]:
    if not re.match('\| \d+ \| \w+ \| \w+ \|.+', line):
        updatedsummary += '%s\n' % line.decode('utf-8')
return updatedsummary

不再跳bug,问题解决

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值