gpt4 book ai didi

python - 为什么 Python 2.x 会抛出字符串格式化 + unicode 异常?

转载 作者:太空宇宙 更新时间:2023-11-04 01:18:59 25 4
gpt4 key购买 nike

我有以下代码。最后一行抛出错误。这是为什么?

class Foo(object):

def __unicode__(self):
return u'\u6797\u89ba\u6c11\u8b1d\u51b0\u5fc3\u6545\u5c45'

def __str__(self):
return self.__unicode__().encode('utf-8')

print "this works %s" % (u'asdf')
print "this works %s" % (Foo(),)
print "this works %s %s" % (Foo(), 'asdf')
print

print "this also works {0} {1}".format(Foo(), u'asdf')
print
print "this should break %s %s" % (Foo(), u'asdf')

错误是“UnicodeDecodeError:‘ascii’编解码器无法解码位置 18 中的字节 0xe6:序号不在范围内 (128)”

最佳答案

当您混合使用 unicode 和字符串对象时,Python 2 会隐式尝试将 unicode 值编码为字符串,或者它会尝试将字节字符串解码为 un​​icode。

您正在混合 unicode、字节字符串和自定义对象,并且您正在触发一系列不混合的编码和解码。

在这种情况下,您的 Foo() 值被插入为一个字符串(使用了 str(Foo())),并且 u'asdf ' 插值会触发模板的解码(因此使用 UTF-8 Foo() 值)以插值 unicode 字符串。此解码失败,因为 ASCII 编解码器无法解码已插入的 \xe6\x9e\x97 UTF-8 字节序列。

在混合类型之前,您应该始终将 Unicode 值显式编码为字节串或将字节字符串解码为 Unicode,因为极端情况很复杂。

显式转换为 unicode() 有效:

>>> print "this should break %s %s" % (unicode(Foo()), u'asdf')
this should break 林覺民謝冰心故居 asdf

当输出变成一个 unicode 字符串时:

>>> "this should break %s %s" % (unicode(Foo()), u'asdf')
u'this should break \u6797\u89ba\u6c11\u8b1d\u51b0\u5fc3\u6545\u5c45 asdf'

否则你会得到一个字节串:

>>> "this should break %s %s" % (Foo(), 'asdf')
'this should break \xe6\x9e\x97\xe8\xa6\xba\xe6\xb0\x91\xe8\xac\x9d\xe5\x86\xb0\xe5\xbf\x83\xe6\x95\x85\xe5\xb1\x85 asdf'

(注意 asdf 也是一个字节串)。

或者,使用 unicode 模板:

>>> u"this should break %s %s" % (Foo(), u'asdf')
u'this should break \u6797\u89ba\u6c11\u8b1d\u51b0\u5fc3\u6545\u5c45 asdf'

关于python - 为什么 Python 2.x 会抛出字符串格式化 + unicode 异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22537722/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com