Skip to main content
 首页 » 编程设计

Python编码问题

2025年05月04日9powertoolsteam

我正在使用一些 python 脚本,得到了一个 UTF8 编码的原始字符串。首先,我将其解码为 utf8,然后完成一些处理,最后我将其编码回 utf8 并插入到 DB(mysql),但 DB 中的字符未以实际格式显示。

str = '<term>Beiträge</term>' 
str = str.decode('utf8') 
... 
... 
... 
str = str.encode('utf8') 

在 txt 文件中找到该字符串的真实形式,但在 MYSQL_DB 中,我发现它是这样的

 <term>"Beiträge</term> 

知道为什么会这样吗? :-(

请您参考如下方法:

假设您正在使用 MySQLdb 库,您需要使用关键字参数创建连接:

use_unicode If True, text-like columns are returned as unicode objects using the connection's character set. Otherwise, text-like columns are returned as strings. columns are returned as normal strings. Unicode objects will always be encoded to the connection's character set regardless of this setting.

&

charset If supplied, the connection character set will be changed to this character set (MySQL-4.1 and newer). This implies use_unicode=True.

您还应该检查数据库表的编码。