Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/305.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python unicode字符串格式_Python - Fatal编程技术网

Python unicode字符串格式

Python unicode字符串格式,python,Python,我只是在一段未注释的代码中看到了这一点。有没有这样做的理由 new_var = u'%s' % (child.tag) 其中child是实例,tag是该实例的属性?看起来这样做更简单: new_var = unicode(child.tag) 它们应该产生相同的结果。我认为直到Python2.5和unicode()函数在此之前都没有添加“u”前缀字符,而现在。另外,如果您需要指定编码类型,unicode()将允许您这样做。它们是相同的,只是偏好的问题。就Python的Zen等而言,实际上

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

 new_var = u'%s' % (child.tag)
其中child是实例,tag是该实例的属性?看起来这样做更简单:

 new_var = unicode(child.tag)

它们应该产生相同的结果。我认为直到Python2.5和unicode()函数在此之前都没有添加“u”前缀字符,而现在。另外,如果您需要指定编码类型,unicode()将允许您这样做。

它们是相同的,只是偏好的问题。就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'

这样做的一个原因可能是代码用来包含一个必须翻译的文本字符串(然后
%s
是一个有用的占位符),或者期望在以后的某个时候包含一个文本