代码之家  ›  专栏  ›  技术社区  ›  Jesse Shieh José Valim

在python中转换为安全的unicode

  •  2
  • Jesse Shieh José Valim  · 技术社区  · 16 年前

    我正在处理未知数据,并尝试使用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 回复  |  直到 16 年前
        1
  •  5
  •   Community CDub    8 年前

    原始编码是什么?我假设“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
  •  3
  •   pixelbeat    16 年前

    在Windows CP1252编码中,0x92是右单引号。

    \ XEF\XBF\XBD是Unicode替换字符的UTF8编码 (插入而不是错误的CP1252字符)。

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

    2种选择: 1。也许您应该使用Unicode(内容,“CP1252”)。 2。如果您想将UTF-8插入数据库,那么您需要对其进行适当的配置。我会把这个答案留给更有知识的人。

        3
  •  1
  •   kdt    16 年前

    “难以置信…”字符串看起来不像utf-8:0x92高于128,因此应该是多字节字符的延续。然而,在这个字符串中,它本身就出现了(显然是一个撇号)。