UnicodeEncodeError 当 __str__ 已经 returns unicode
UnicodeEncodeError when __str__ already returns unicode
我们有以下格式化字符串:
'{}: {}.'.format(message, object)
其中提出:
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-3: ordinal not in range(128)
对象的字符串是非 ascii 字符串,但该方法被重写,因此它 returns 是一个 unicode 字符串:
def __str__(self):
return unicode(self.name)
那为什么要提出 UnicodeEncodeError
?我能做些什么来修复它?
我试过将字符串转换为 unicode:
u'{}: {}.'.format(message, object)
但这会弄乱对象的字符串。它 returns \xf1\xf1\xf1\xf1
而不是 ññññ
.
我推荐函数decode
和encode
,如下:
class A(object):
def __str__(self):
return "速度快".decode("utf-8", "ignore")
obj = A()
print u"{}".format(obj)
添加u
在Python2中,普通字符串是字节串。 __str__
应该 永远不会 return 一个 unicode 字符串:你正在违反 str
合同。如果您需要为您的对象进行 unicode 转换,请使用 __unicode__
特殊函数:
def __unicode__(self):
return unicode(self.name)
甚至更好 return self.name.decode(encoding)
其中编码是 self.name
.
的编码
切勿在没有显式编码的情况下混合使用 unicode 字符串和字节字符串。所以正确的做法是:
'{}: {}.'.format(message, unicode(object).encode(encoding))
在这里,编码再次表示您想要的外部表示形式。 Windows 上的常见编码是 Latin1
或 cp1252
,Linux
上通常是 utf-8
我们有以下格式化字符串:
'{}: {}.'.format(message, object)
其中提出:
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-3: ordinal not in range(128)
对象的字符串是非 ascii 字符串,但该方法被重写,因此它 returns 是一个 unicode 字符串:
def __str__(self):
return unicode(self.name)
那为什么要提出 UnicodeEncodeError
?我能做些什么来修复它?
我试过将字符串转换为 unicode:
u'{}: {}.'.format(message, object)
但这会弄乱对象的字符串。它 returns \xf1\xf1\xf1\xf1
而不是 ññññ
.
我推荐函数decode
和encode
,如下:
class A(object):
def __str__(self):
return "速度快".decode("utf-8", "ignore")
obj = A()
print u"{}".format(obj)
添加u
在Python2中,普通字符串是字节串。 __str__
应该 永远不会 return 一个 unicode 字符串:你正在违反 str
合同。如果您需要为您的对象进行 unicode 转换,请使用 __unicode__
特殊函数:
def __unicode__(self):
return unicode(self.name)
甚至更好 return self.name.decode(encoding)
其中编码是 self.name
.
切勿在没有显式编码的情况下混合使用 unicode 字符串和字节字符串。所以正确的做法是:
'{}: {}.'.format(message, unicode(object).encode(encoding))
在这里,编码再次表示您想要的外部表示形式。 Windows 上的常见编码是 Latin1
或 cp1252
,Linux
utf-8