'latin-1' codec can't encode character 的解決方案
阿新 • • 發佈:2019-01-10
分析一個字串,並更新資料庫的時候,出現瞭如下錯誤:
'latin-1' codec can't encode character u'\u017e' in position 11: ordinal not in range(256)
進行了一些研究發現,原因是,資料庫的編碼和資料來源的編碼不一致,並且包含了不能處理的字元。
有兩種方法可用,一個是先預先處理一下字串,二是設定資料庫引數
1. 處理字串
'latin-1' codec can't encode character u'\u017e' in position 11: ordinal not in range(256)
進行了一些研究發現,原因是,資料庫的編碼和資料來源的編碼不一致,並且包含了不能處理的字元。
有兩種方法可用,一個是先預先處理一下字串,二是設定資料庫引數
1. 處理字串
- >>> u
= u'hello\u2013world'
- >>> u.encode('latin-1',
'replace') # replace it with a question mark
- 'hello?world'
- >>> u.encode('latin-1',
'ignore') # ignore it
- 'helloworld'
- 或者根據需求進行處理
- >>> u.replace(u'\u2013',
'-').encode('latin-1')
- 'hello-world'
- If you aren't required to output Latin-1, then UTF-8 is a common and preferred choice. It is recommended by the W3C and nicely encodes all Unicode code points:
- >>> u.encode('utf-8')
- 'hello\xe2\x80\x93world
- db.set_character_set('utf8')
- dbc.execute('SET NAMES utf8;')
- dbc.execute('SET CHARACTER SET utf8;')
- dbc.execute('SET character_set_connection=utf8;')