【问题标题】:Converting to safe unicode in python在 python 中转换为安全的 unicode
【发布时间】:2009-05-16 22:04:14
【问题描述】:

我正在处理未知数据并尝试使用 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

感谢任何帮助!

【问题讨论】:

    标签: python django unicode


    【解决方案1】:

    原始编码是什么?我假设“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'
    

    【讨论】:

      【解决方案2】:

      0x92 是 windows cp1252 编码中的右单引号。

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

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

      2 个选项: 1. 也许你应该使用 unicode(content,"cp1252") 2. 如果你想将 UTF-8 插入数据库,那么你需要适当地配置它。我会把这个答案留给其他知识渊博的人

      【讨论】:

        【解决方案3】:

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

        【讨论】:

          猜你喜欢
          • 2014-04-03
          • 2011-06-12
          • 2011-10-10
          • 2018-08-16
          • 2018-05-09
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多