Why python str.format does not call str ()

I have the following class

class A(object):
  def __unicode__(self):
    return u'A'

  def __str__(self):
    return 'AA'

>>> u"{}".format(A())
u'A'
>>> "{}".format(A())
'AA'
>>> str(A())
'AA'

According to the documentation ,

"Harold smart {0! S}" # Calls str () on the first argument

Why does this still return u'A 'not u'AA' ??

>>> u"{0!s}".format(A())
u'A'

I would expect it to be the same as

>>> u"{}".format(str(A()))
u'AA'
+3
source share
1 answer

I think this is a (minor) error in the documentation. str.formatcalls strif you pass the code !sin a format string, but unicode.formatcalls unicode.

, , Python 3, Unicode !s str. Python 3.0 Python 2.6, , .

+4

Source: https://habr.com/ru/post/1727289/


All Articles