Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unicode string formatting

Tags:

python

I just saw this in a piece of uncommented code. Is there ever a reason to do this?

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

where child is an instance and tag is an attribute of that instance? It seems like this does it more simply:

 new_var = unicode(child.tag)
like image 291
Adam Nelson Avatar asked Sep 18 '26 12:09

Adam Nelson


1 Answers

They are identical, and it's just a matter of preference. In terms of the Zen of Python and such, there's really not a "better" way as both are explicit in that they are getting a unicode representation of child.tag. Mechanically they do the same thing:

>>> 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'
like image 134
Daniel DiPaolo Avatar answered Sep 21 '26 00:09

Daniel DiPaolo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!