Formatting strings in unicode

I just saw this in a piece of unchained code. Is there a reason for this?

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

where child is an instance and tag is an attribute of this instance? This seems to make it easier:

 new_var = unicode(child.tag)
+3
source share
3 answers

They are identical, and this is only a matter of preference. In terms of Zen Python, etc. There really is no “better” way, since both explicitly express that they get a unicode representation child.tag. Mechanically they do the same:

>>> 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'
+2
source

, , , ( %s ), , , - .

+2

They should give the same results. I think the prefix character 'u' was not added until Python 2.5 and the unicode () function appeared before that, and now. In addition, if you need to specify the type of encoding, unicode () will allow you to do this.

+1
source

Source: https://habr.com/ru/post/1793086/


All Articles