我有一个带有文本字段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 问题真的很烦人!)