简体   繁体   中英

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__ ?

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

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

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

Firstly, is there one?

Sure (sort of). A unicode format string will convert the format values to unicode, implying that obj.__unicode__ will be called ( reference ).

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

Aside from the above, there's no particular reason why you couldn't be explicit:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM