【发布时间】:2012-10-26 03:00:00
【问题描述】:
我有一个带有文本字段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)
我想我使用了encode/decode/utf-8/ascii/replace/ignore/...的所有可能组合
(python unicode 问题真的很烦人!)
【问题讨论】:
标签: python