【发布时间】:2011-08-05 13:09:55
【问题描述】:
我已经想出了这个问题,但经过一些测试后,我决定创建一个包含更具体信息的新问题:
我正在从我们的 Active Directory 中使用 python-ldap(和 Python 2.7)读取用户帐户。这确实很好用,但我遇到了特殊字符的问题。在控制台上打印时,它们看起来确实像 UTF-8 编码的字符串。目标是将它们写入 MySQL 数据库,但我并没有从一开始就将这些字符串转换为正确的 UTF-8。
示例(fullentries 是我的包含所有 AD 条目的数组):
fullentries[23][1].decode('utf-8', 'ignore')
print fullentries[23][1].encode('utf-8', 'ignore')
print fullentries[23][1].encode('latin1', 'ignore')
print repr(fullentries[23][1])
手动插入字符串的第二个测试如下:
testentry = "M\xc3\xbcller"
testentry.decode('utf-8', 'ignore')
print testentry.encode('utf-8', 'ignore')
print testentry.encode('latin1', 'ignore')
print repr(testentry)
第一个例子ist的输出:
M\xc3\xbcller
M\xc3\xbcller
u'M\\xc3\\xbcller'
编辑:如果我尝试用 .replace('\\\\','\\) 替换双反斜杠,输出保持不变。
第二个例子的输出:
Müller
M�ller
'M\xc3\xbcller'
有什么方法可以正确编码 AD 输出?我已经阅读了很多文档,但都指出 LDAPv3 为您提供了严格的 UTF-8 编码字符串。 Active Directory 使用 LDAPv3。
我的老问题这个话题在这里:Writing UTF-8 String to MySQL with Python
编辑:添加代表信息
【问题讨论】:
标签: python unicode utf-8 active-directory