开发者

Python string format character for __unicode__?

First开发者_运维百科ly, 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))
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜