Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python string format character for __unicode__?

Firstly, is there one?

If not, is there a nice way to force something like

print '%s' % obj

to call obj.__unicode__ instead of obj.__str__?

like image 566
mpen Avatar asked Jun 24 '10 04:06

mpen


2 Answers

Just use a unicode format string, rather than having a byte string in that role:

>>> class X(object):
...   def __str__(self): return 'str'
...   def __unicode__(self): return u'unicode'
... 
>>> x = X()
>>> print u'%s' % x
unicode
like image 107
Alex Martelli Avatar answered Oct 16 '22 09:10

Alex Martelli


No. It wouldn't make sense for this to be the case.

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

like image 1
Mike Graham Avatar answered Oct 16 '22 09:10

Mike Graham