Python 字符串格式化字符 __unicode__ 是什么?

5 投票
3 回答
2082 浏览
提问于 2025-04-16 00:22

首先,是否有这样的东西?

如果没有,有没有什么好的方法可以强制像下面这样的代码

print '%s' % obj

去调用 obj.__unicode__ 而不是 obj.__str__ 呢?

3 个回答

0

首先,真的有吗?

当然有(算是吧)。一个unicode格式的字符串会把格式中的值转换成unicode,这意味着会调用obj.__unicode__这个方法(参考链接)。

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

除了上面提到的,实际上你也可以明确地指定:

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

不,这样说没有道理。

print (u"%s" % obj).encode(some_encoding) 这段代码会使用 obj.__unicode__

4

只需要使用一个unicode格式的字符串,而不是用字节字符串来代替:

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

撰写回答