python unicode 转utf_将Unicode转换为UTF-8 Python

I am working with a database that has throughout it scattered characters like this: ’. I need to take this from the database, convert it to UTF-8, and then import it into a different database, using python. When printed to the Windows Command Prompt, these characters look like this: \xe2\u20ac\u2122. I have tried various combinations of .decode(), .encode(), and unicode() to convert the data, but Im really stuck.

解决方案

Always decode on input, and encode on output. (There ought to be handy mnemonic for this: perhaps "take your code [coat] off when you come indoors".)

Decode on input: You say that the database encoding is "UTF_8_bin". Are you using MySQL-Python? If so, then you can set the use_unicode option when you connect to the database. Then all strings are fetched from the database in Unicode, so you don't have worry about decoding them.

Encode on output: You can find out the current character encoding (or "code page" as they call it in Windows) with the chcp command. Let's suppose it's code page 1252. Then you can write

print text.encode('windows-1252')

to produce something that you can read from the Windows command line.

If you're writing the strings back to another MySQL database using MySQL-Python, you shouldn't need to do anything special: MySQL-Python claims that "you can always write Unicode strings" (regardless of whether you specified use_unicode when you opened the connection).

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值