python将字符编码改为utf_8

2024-09-28 21:24:01 发布

您现在位置:Python中文网/ 问答频道 /正文

实际数据:CN=usernameOU=CompanyNameDC=companyDC=intra(它在MySQL数据库中的显示方式),当我获取这些数据时,它在python变量中的显示方式(从MySQL检索):CN=usernameOU=CompanyNameDC=companyDC=intra

当我尝试这个

truestr = unicode(str,'utf-8');

引发异常,并显示以下消息:

'ascii' codec can't decode byte 0xc4 in position 4: ordinal not in range(128)

我如何解决这个问题?(我使用python2.6)


Tags: 数据in数据库mysqlunicodeusernameoudc
3条回答

您可以用以下方法检查编码:

>>> import sys
>>> sys.getdefaultencoding()
'utf-8'
>>> 

如果编码是ascii,则设置为utf-8

  1. 打开以下文件(我使用的是python2.7):

    /usr/lib/python2.7/sitecustomize.py

  2. 然后更新以下内容到utf-8

    sys.setdefaultencoding("utf-8")

[编辑2]

你能在旅游代码中添加以下内容吗检查:在

^{pr2}$

转到此文件

vi /usr/lib/python2.7/site-packages/sitecustomize.py

添加此文本

^{pr2}$

此错误意味着您的消息已经是对象,不需要解码。在

当您执行以下操作时:

truestr = unicode(string, 'utf-8')

变量string首先使用默认的'ascii'编解码器隐式转换为str类型。当然,它会失败,因为字符串包含非ascii字符。在

如果要将string写成UTF-8,请使用string.encode('utf-8')。在


注意:我已经将您的str变量重命名为string,因为它与内置的str类型冲突。命名变量str(或int,或float等)是一种非常糟糕的样式。在

相关问题 更多 >