在python中转换为安全的unicode

时间:2009-05-16 22:04:14

标签: python django unicode

我正在处理未知数据并尝试使用Python / Django插入MySQL数据库。我收到一些我不太了解的错误,正在寻求帮助。这是错误。

Incorrect string value: '\xEF\xBF\xBDs m...'

我的猜测是字符串没有正确转换为unicode?这是我的unicode转换代码。

s = unicode(content, "utf-8", errors="replace")

如果没有上面的unicode转换,我得到的错误是

'utf8' codec can't decode byte 0x92 in position 31: unexpected code byte. You passed in 'Fabulous home on one of Decatur\x92s most

感谢任何帮助!

3 个答案:

答案 0 :(得分:5)

原始编码是什么?我假设“cp1252”,来自pixelbeat's回答。在这种情况下,你可以做

>>> orig # Byte string, encoded in cp1252
'Fabulous home on one of Decatur\x92s most' 

>>> uni = orig.decode('cp1252')
>>> uni # Unicode string
u'Fabulous home on one of Decatur\u2019s most'

>>> s = uni.encode('utf8')  
>>> s # Correct byte string encoded in utf-8
'Fabulous home on one of Decatur\xe2\x80\x99s most'

答案 1 :(得分:3)

0x92是windows cp1252编码中的单个卷曲引号。

\ xEF \ xBF \ xBD是unicode替换字符的UTF8编码 (插入而不是错误的cp1252字符)。

所以看起来您的数据库不接受有效的UTF8数据?

2个选项:  也许你应该使用unicode(内容,“cp1252”)  2.如果要将UTF-8插入数据库,则需要对其进行适当的配置。我会把这个答案留给其他更有见识的人

答案 2 :(得分:1)

“Fabulous ...”字符串看起来不像utf-8:0x92高于128,因此应该是多字节字符的延续。但是,在该字符串中它出现在它自己(显然代表撇号)。