__str__已经返回unicode时出现UnicodeEncodeError

时间:2019-02-26 10:57:54

标签: python string python-2.7 unicode

我们有以下格式的字符串:

'{}: {}.'.format(message, object)

哪个加薪:

UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-3: ordinal not in range(128)

该对象的字符串是非ASCII字符,但是该方法被覆盖,因此它返回一个unicode字符串:

def __str__(self):
    return unicode(self.name)

为什么要提出UnicodeEncodeError?我该怎么解决?

我尝试将字符串转换为unicode:

u'{}: {}.'.format(message, object)

但是这弄乱了对象的字符串。它返回\xf1\xf1\xf1\xf1而不是ññññ

2 个答案:

答案 0 :(得分:3)

在Python 2中,普通字符串是字节字符串。并且__str__应该绝不返回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上是Latin1cp1252,在Linux上通常是utf-8

答案 1 :(得分:0)

我推荐功能 notificationModel.setPackageNmae(sbn.getPackageName()); notificationModel.setTitle(sbn.getNotification().extras.getString("android.title")); notificationModel.setBody(sbn.getNotification().extras.getString("android.text")); notificationModel.setIcon(sbn.getNotification().extras.getInt("android.icon")); notificationModel.setKey(sbn.getId()); decode,如下所示:

encode

添加class A(object): def __str__(self): return "速度快".decode("utf-8", "ignore") obj = A() print u"{}".format(obj)