我有一些用UTF-8编码的文本。“事前事后”它是从网络上获取的。“-”字符是问题所在。如果尝试使用复制和粘贴直接从命令行打印:
>>> text = 'Before – after.'
>>> print text
Before – after.但是,如果保存为文本文件并尝试打印:
>>> for line in ('file.txt','r'):
>>> print line
Before û after.我很确定这是某种UTF-8编码/解码错误,但它让我摸不着头脑。我尝试过解码或重新编码,但也不是这样。
>>> for line in ('file.txt','r'):
>>> print line.decode('utf-8')
UnicodeDecodeError: 'utf8' codec can't decode byte 0x96 in position 7: invalid start byte
>>> for line in ('file.txt','r'):
>>> print line.encode('utf-8')
UnicodeDecodeError: 'utf8' codec can't decode byte 0x96 in position 7: invalid start byte发布于 2017-04-30 23:29:08
这是因为无法对非ascii字符进行编码或解码。您可以将其去掉,然后打印ascii值。看一下这个问题:UnicodeDecodeError: 'utf8' codec can't decode byte 0xa5 in position 0: invalid start byte
https://stackoverflow.com/questions/43707974
复制相似问题