'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;')
  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值