Python string format character for __unicode__?

Firstly, is there one?

If not, is there a good way to get something like

print '%s' % obj

to call obj.__unicode__instead obj.__str__?

+5
source share
3 answers

Just use a unicode format string, not a string in this role:

>>> class X(object):
...   def __str__(self): return 'str'
...   def __unicode__(self): return u'unicode'
... 
>>> x = X()
>>> print u'%s' % x
unicode
+4
source

No. That would not make sense.

print (u"%s" % obj).encode(some_encoding)will use obj.__unicode__.

+1
source

-, ?

(). Unicode unicode, , obj.__unicode__ ().

u'this is a %s' % ('unicode string')

, , :

print '%s' % (unicode(obj))
0

All Articles