>>> s = u"wxPython: Windows Styles and Events Hunter « The Mouse Vs. The Python"
>>> s.encode('ascii')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\xab' in position 43: ordinal not in range(128)
编码的默认模式是
'strict'
,这将抛出一个错误。在如果您的数据库只接受ASCII,那么您别无选择,只能进行有损编码。在
^{pr2}$'ignore'
模式下,将跳过所有无法编码的字节:在
'replace'
模式下,它们被替换为?字符:最后,还有{}:
从你在其他答案中的评论,我可以看出你得到的错误是:
由于
«
被编码为\xab
,这意味着该字符串可能编码在iso-8995-1、iso-8995-15、windows-1252/latin-1中。这可能与计算机的区域设置有关。在您只需在传递给MongoDB之前对其进行解码,MongoDB支持Unicode字符串(正如您所断言的,它不限于ASCII):
^{pr2}$现在可以将
document
传递给Python MongoDB驱动程序。在要使代码可移植,可以使用编解码器别名
mbcs
(代替“拉丁语-1”)。mbcs
会自动转换为配置的Windows区域设置(感谢@roeland)相关问题 更多 >
编程相关推荐