Python編碼問題

Python處理編碼問題時老是出現以下錯誤:python

UnicodeDecodeError: 'ascii' codec can't decode byte 0xe5 in position 0: ordinal not in range(128)編碼

 

出現這個問題時強烈推薦看下下面的博客,博客裏面講的很是清楚,也很是易懂。spa

http://in355hz.iteye.com/blog/1860787code

 

總結下大體是:blog

python裏有兩種字符串類型,一種是str,一種是unicode,用引號定義的字符串就是str (如'str'),用u加引號定義的字符串就是unicode(如u'str'),若是不知道你的字符串屬於那種類型,可使用以下代碼進行檢測:ci

    string = 'hello'
    uni_str = u'hello'
    print isinstance(string, str)        #輸出True
    print isinstance(string, unicode)    #輸出False
    print isinstance(uni_str, str)     #輸出False
    print isinstance(uni_str, unicode) #輸出True

而後str與unicode的轉換以下:unicode

    string = 'hello'
    uni_str = u'hello'

    print isinstance(string.decode('utf8'), unicode)  #返回True
    print isinstance(uni_str.encode('utf8'), str)     #返回True

若是decode或者encode使用錯了,如對str使用encode,對unicode使用decode就會報上面的錯誤。字符串

相關文章
相關標籤/搜索