蟒蛇:UNICODE函数VSü前缀
问题描述:
我遇到了麻烦,在我的Django项目UnicodeEncodeError
,并最终通过改变返回值解决问题(太多的无奈后)在故障从蟒蛇:UNICODE函数VSü前缀
return unicode("<span><b>{0}</b>{1}<span>".format(val_str, self.text))
__unicode__
方法
到
return u"<span><b>{0}</b>{1}<span>".format(val_str, self.text)
但我很困惑,为什么这个工作(或者说,为什么在首位的问题)。 u
前缀和unicode
函数不会做同样的事情吗?当在一个控制台尝试它,他们似乎给了相同的结果:
# with the function
test = unicode("<span><b>{0}</b>{1}<span>".format(2,4))
>>> test
u'<span><b>2</b>4<span>'
>>> type(test)
<type 'unicode'>
# with the prefix
test = u"<span><b>{0}</b>{1}<span>".format(2,4)
>>> test
u'<span><b>2</b>4<span>'
>>> type(test)
<type 'unicode'>
但似乎编码以某种方式做不同的视的二手什么。这里发生了什么?
答
你的问题在于你申请的东西unicode()
到;你的两个表达式是而不是等效。
unicode("<span><b>{0}</b>{1}<span>".format(val_str, self.text))
适用unicode()
到的结果:
"<span><b>{0}</b>{1}<span>".format(val_str, self.text)
而
u"<span><b>{0}</b>{1}<span>".format(val_str, self.text)
是等价的:
unicode("<span><b>{0}</b>{1}<span>").format(val_str, self.text)
注意右括号的位置!
所以,你的第一个版本格式第一,只有然后转换格式为Unicode的结果。这是一个重要的区别!
当使用str.format()
与unicode
值,则这些值被传递到str()
,其隐含编码那些字符串ASCII。这将导致你的异常:
>>> 'str format: {}'.format(u'unicode ascii-range value works')
'str format: unicode ascii-range value works'
>>> 'str format: {}'.format(u"unicode latin-range value doesn't work: å")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe5' in position 40: ordinal not in range(128)
不要紧,你在调用的结果unicode()
;这个例外已经被提出。
与unicode.format()
格式化,另一方面有没有这样的问题:
>>> u'str format: {}'.format(u'unicode lating-range value works: å')
u'str format: unicode lating-range value works: \xe5'
+0
啊,这就是诀窍!在str上调用'format'而不是unicode会尝试将参数转换为ascii,这不起作用。 – Pterosaur 2014-09-22 21:07:14
什么Python版本是什么? – 2014-09-22 20:54:32
2.7。 对不起,这与Python 3现在处理字符串/ unicode的方式有所不同。 – Pterosaur 2014-09-22 20:55:35
在unicode函数版本中,您将格式化为“unicodize”。格式化的问题是什么? – tdelaney 2014-09-22 20:55:41