【问题标题】:UnicodeDecodeError (once again) with format() but not with concatenationUnicodeDecodeError(再次)与 format() 但不是与连接
【发布时间】:2012-10-26 03:00:00
【问题描述】:

我有一个带有文本字段titletext 的类块。当我想打印它们时,我得到(惊喜,惊喜!)UnicodeDecodeError。当我尝试格式化输出字符串时,它给了我一个错误,但是当我只是连接文本和标题并返回它时,我没有收到任何错误:

class Chunk:
  # init, fields, ...

  # this implementation will give me an error
  def __str__( self ):
    return u'{0} {1}'.format ( enc(self.text), enc(self.title) )

  # but this is OK - all is printed without error
  def __str__( self ):
    return enc(self.text) + enc(self.title)

def enc(x):
  return x.encode('utf-8','ignore') # tried many combinations of arguments...


c = Chunk()
c.text, c.title = ... # feed from external file
print c

呸!错误!

return u'{0} {1}'.format ( enc(self.text), enc(self.title) )
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 in position 2844: ordinal not in range(128)

我想我使用了encode/decode/utf-8/ascii/replace/ignore/...的所有可能组合

(python unicode 问题真的很烦人!)

【问题讨论】:

标签: python


【解决方案1】:
  1. 当您返回 unicode 时,您应该 override __unicode__, not __str__
  2. 没有必要调用.encode(),因为输入已经是一个unicode。随便写

    def __unicode__(self):
        return u"{0} {1}".format(self.text, self.title)
    

【讨论】:

    【解决方案2】:

    避免2.x python的unicode问题最简单的方法就是将整体编码设置为utf-8,否则这样的问题会在突然的地方不断出现:

    import sys
    reload(sys)
    sys.setdefaultencoding('utf-8')
    

    【讨论】:

    • 这是个坏主意。当然,会出现问题,您需要解决它们 - 您必须知道您使用的数据(字符)并处理所有边缘情况。 setdefaultencoding 只会隐藏错误。
    猜你喜欢
    • 2015-11-20
    • 2016-03-01
    • 1970-01-01
    • 2019-05-08
    • 2019-07-05
    • 2012-05-15
    • 2017-05-30
    • 2015-10-24
    • 2014-05-31
    相关资源
    最近更新 更多