string interpolation mystery in Python 2.6

Scott David Daniels Scott.Daniels at Acm.Org
Wed Sep 16 16:44:00 CEST 2009


Alan G Isaac wrote:
> George Brandl explained it to me this way:
>         It's probably best explained with a bit of code:
> 
>         >>> class C(object):
>         ...  def __str__(self): return '[str]'
>         ...  def __unicode__(self): return '[unicode]'
>         ...
>         >>> "%s %s" % ('foo', C())
>         'foo [str]'
>         >>> "%s %s" % (u'foo', C())
>         u'foo [unicode]'
>  I.e., as soon as a Unicode element is interpolated into 
> a string, further interpolations automatically request 
> Unicode via __unicode__, if it exists.

Even more fun (until you know what is going on):
     >>> c = C()
     >>> "%s %s %s" % (c, u'c', c)
     u'[str] c [unicode]'

--Scott David Daniels
Scott David Daniels at Acm.Org



More information about the Python-list mailing list