今天在写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,问题解决