這 是因為遇到了非法字符——尤其是在某些用C/C++編寫的程序中,全角空格往往有多種不同的實現方式,比如\xa3\xa0,或者\xa4\x57,這些 字符,看起來都是全角空格,但它們並不是“合法”的全角空格(真正的全角空格是\xa1\xa1),因此在轉碼的過程中出現了異常。
這樣的問題很讓人頭疼,因為只要字符串中出現了一個非法字符,整個字符串——有時候,就是整篇文章——就都無法轉碼。
解決辦法:
s.decode(‘gbk’, ‘ignore’).encode(‘utf-8′)
因為decode的函數原型是decode([encoding], [errors='strict']),可以用第二個參數控制錯誤處理的策略,默認的參數就是strict,代表遇到非法字符時拋出異常;
如果設置為ignore,則會忽略非法字符;
如果設置為replace,則會用?取代非法字符;
如果設置為xmlcharrefreplace,則使用XML的字符引用。
python文檔
decode( [encoding[, errors]])
Decodes the string using the codec registered for encoding. encoding defaults to the default string encoding. errors may be given to set a different error handling scheme. The default is ’strict’, meaning that encoding errors raise UnicodeError. Other possible values are ‘ignore’, ‘replace’ and any other name registered via codecs.register_error, see section 4.8.1.