1. 程式人生 > >'latin-1' codec can't encode character 的解決方案

'latin-1' codec can't encode character 的解決方案

分析一個字串,並更新資料庫的時候,出現瞭如下錯誤:
'latin-1' codec can't encode character u'\u017e' in position 11: ordinal not in range(256)

進行了一些研究發現,原因是,資料庫的編碼和資料來源的編碼不一致,並且包含了不能處理的字元。

有兩種方法可用,一個是先預先處理一下字串,二是設定資料庫引數

1. 處理字串
  1. >>> u = u'hello\u2013world'
  2. >>> u.encode('latin-1', 'replace') # replace it with a question mark
  3. 'hello?world'

  4. >>> u.encode('latin-1', 'ignore') # ignore it
  5. 'helloworld'
  6. 或者根據需求進行處理
  7. >>> u.replace(u'\u2013', '-').encode('latin-1')
  8. 'hello-world'
  9. 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:
  10. >>> u.encode('utf-8')
  11. 'hello\xe2\x80\x93world
2. 設定資料庫
  1. db.set_character_set('utf8')
  2. dbc.execute('SET NAMES utf8;')
  3. dbc.execute('SET CHARACTER SET utf8;')
  4. dbc.execute('SET character_set_connection=utf8;')