python編碼錯誤

2021-08-01 05:45:25 字數 1834 閱讀 3675

錯誤:

1.unicodewarning: unicode equal comparisonfailed to convert both arguments to unicode - interpreting them as beingunequal

2.unicodedecodeerror: 'ascii' codec can't decode byte 0xef in position 0: ordinal not in range(128)

先了解一下unicode和utf-8的區別。

unicode指的是萬國碼,是一種「字碼表」。而utf-8是這種字碼表儲存的編碼方法。unicode不一定要由utf-8這種方式編成bytecode儲存,也可以使用utf-16,utf-7等其他方式。目前大多都以utf-8的方式來變成bytecode。

其次,python中字串型別分為byte string 和 unicode string兩種。

如果在python檔案中指定編碼方式為utf-8(#coding=utf-8),那麼所有帶中文的字串都會被認為是utf-8編碼的byte string(例如:mystr="你好"),但是在函式中所產生的字串則被認為是unicode string。

問題就出在這邊,unicode string 和 byte string 是不可以混合使用的,一旦混合使用了,就會產生這樣的錯誤。例如:

self.response.out.write("你好"+self.request.get("argu"))

其中,"你好"被認為是byte string,而self.request.get("argu")的返回值被認為是unicode string。由於預設的解碼器是ascii,所以就不能識別中文byte string。然後就報錯了。

以下有兩個解決方法:

1.將字串全都轉成byte string。

self.response.out.write("你好"+self.request.get("argu").encode("utf-8"))

2.將字串全都轉成unicode string。

self.response.out.write(u"你好"+self.request.get("argu"))

byte string轉換成unicode string可以這樣轉unicode(unicodestring, "utf-8")

python處理字串或中文時出現以下錯誤:

"unicodedecodeerror: 'ascii' codec can't decode byte 0xe9 in position 0: ordinal not in range(128)"

解決辦法,在該python檔案的前面加上如下幾句,問題得到解決。

import sys

default_encoding = 'utf-8'

if sys.getdefaultencoding() != default_encoding:

reload(sys)

sys.setdefaultencoding(default_encoding)

總結:

首先 保證**開頭有#encoding=utf-8 或者#-*- encoding: utf-8 -*-

最後 再參考文章2中解決辦法的**複製貼上到自己的**中

折騰了很久的中文編碼問題,最終在文章2的方法下解決了。

python中文編碼錯誤 使用Python編碼錯誤

指定源 編碼對我很有用。這是 示例 頂部的 這應該在python檔案的頂部定義。在 usr bin python coding iso 8859 15 value instala o de eletr nicos.decode iso 8859 15 print value prints insta...

Python編碼錯誤處理

在將字串寫入檔案時,執行f.write str 後台總是報錯 unicodeencodeerror ascii codec can t encode character u u6211 in position 0 ordinal not in range 128 即ascii碼無法被轉換成unico...

python編碼問題錯誤處理

在做爬蟲後處理語料實現bsbi演算法索引程式遇到的問題 python開啟或者寫入txt時遇到的問題 問題集合 unicodeencodeerror gbk codec can t encode character ufeff in position 0 illegal multibyte seque...