unicode字符串格式

时间:2011-02-18 16:15:59

标签: python

我刚刚在一段未注释的代码中看到了这一点。有没有理由这样做?

 new_var = u'%s' % (child.tag)

其中child是实例,tag是该实例的属性?看起来这更简单:

 new_var = unicode(child.tag)

3 个答案:

答案 0 :(得分:2)

它们是相同的,这只是一个偏好问题。就Python的Zen而言,实际上并不是一种“更好”的方式,因为它们都是明确的,因为它们获得了child.tag的unicode表示。从机械上讲,他们做同样的事情:

>>> class foo(object):
    def __init__(self, val):
        self.val = val

    def __str__(self):
        return "str: %s" % self.val
    def __unicode__(self):
        return "unicode: %s" % self.val


>>> f = foo("bar")
>>> u'%s' % f
u'unicode: bar'
>>> unicode(f)
u'unicode: bar'
>>> '%s' % f
'str: bar'

答案 1 :(得分:2)

这样做的一个原因可能是,用于包含必须翻译的文字字符串的代码(然后%s是一个有用的占位符),或者预计稍后会包含一个文字。< / p>

答案 2 :(得分:1)

他们应该产生相同的结果。我认为直到Python 2.5和unicode()函数之前的'u'前缀字符才被添加,现在。此外,如果您需要指定编码类型,unicode()将允许您这样做。