你好,我想将字符串保存到变量中,如下所示:
msg=_(u'Uživatel <a href="{0}">{1} {3}</a>').format(request.user.get_absolute_url, request.user.first_name, request.user.last_name)
但是,由于插入的变量包含带有重音符号的字符,例如šI get UnicodeDecodeError,即使我已经通过# -*- coding: utf-8 -*-
设置了编码
奇怪的是(IMHO),当我通过连接如下变量创建这个字符串时,它是有效的:
^{pr2}$我不知道为什么它不应该工作,因为它正在运行的项目,我不得不多次使用这样的语句。在
如果你对如何解决这个问题有任何建议,我将非常感激。在
解决方案非常简单,我使用了}。抱歉打扰你了。在
get_absolute_url
而不是{检查要格式化的参数类型,我猜它们是'str',不是'unicode'。 在使用它们之前,对它们进行适当的编码,例如:
(}语句仅用于演示目的)
相应地使用其他值。在
if
和{您的
user
查找返回的是编码的bytestring,而不是Unicode对象。在当Python2.x被要求连接Unicode和bytestrings编码时,它通过使用默认编码将bytestring解码为Unicode来实现的,默认编码是
ascii
,除非您进行一些更改。# -*- coding: utf-8 -*-
指令设置源代码的编码,而不是系统默认编码。在从测试
format
来看,它似乎试图转换参数以匹配左侧的类型。在在2.x下,只要您使用的bytestring可以使用
ascii
解码,一切都将正常工作:当然,您正在另一个Unicode对象中格式化:
^{pr2}$如果在格式化之前省略
u
,则会得到一个UnicodeEncodeError
:相反,如果将非ascii字节的编码字符串格式化为Unicode对象,则会得到一个
UnicodeDecodeError
:我首先检查}构建的东西应该是Unicode对象,所以我首先打赌
get_absolute_url
实现。有效的url永远不能包含未转义的非ascii字符,因此它们应该始终可以被ascii解码,但是如果您使用的是标准Django模型first_name
和{get_absolute_url
的错误实现。在相关问题 更多 >
编程相关推荐