Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/kotlin/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python UnicodeDecodeError(再次)与format()一起使用,但不与串联一起使用_Python - Fatal编程技术网

Python UnicodeDecodeError(再次)与format()一起使用,但不与串联一起使用

Python UnicodeDecodeError(再次)与format()一起使用,但不与串联一起使用,python,Python,我有一个带有文本字段title和text的类块。当我想要打印它们时,我会得到(惊喜,惊喜!)UnicodeDecodeError。当我试图格式化输出字符串时,它会给我一个错误,但当我只是连接文本和标题并返回它时,我没有得到错误: class Chunk: # init, fields, ... # this implementation will give me an error def __str__( self ): return u'{0} {1}'.format (

我有一个带有文本字段
title
text
的类块。当我想要打印它们时,我会得到(惊喜,惊喜!)
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)
我想我使用了
编码
/
解码
/
utf-8
/
ascii
/
替换
/
忽略
/

(python unicode问题真的令人恼火!)

  • 当您返回unicode时,您应该这样做
  • 无需调用
    .encode()
    ,因为输入已经是unicode。只要写

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

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

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

    把你的输入放在例外的地方。你读过了吗?这是个坏主意。当然,问题会出现,你需要解决它们——你必须知道你使用的是什么数据(字符),并处理所有的边缘情况
    setdefaultencoding
    只会隐藏bug。