issue with string.Template

Raymond Hettinger python at rcn.com
Sun Sep 11 21:36:18 EDT 2005


Michele Simionato wrote:
> This is somewhat in between a bug report and a feature request.
> I was using the new string.Template class and I have run into a
> few issues that I traced back to the usage of the idiom
>
> '%s' % val
>
> in the 'convert' helper function in Template.substitute.
>
> I do not understand why '%s' % val was used instead of just
> str(val).

The reason is written in the code comments:

"""
# We use this idiom instead of str() because the latter will
# fail if val is a Unicode containing non-ASCII characters.
"""



> P.S. at the end, the problem is that string interpolation with
> positional arguments is somewhat of a hack, but fixing this will
> have to wait until Python 3000 ...

The plan for Py3.0 is to have a formatting function that doesn't have
the same tuple vs scalar issue.



> So, take this as a bug report if the behavior is not intended and
> as a feature request if the current behaviour is the intended
> one ;)

Feel free to post a SF report.  If Barry wants to alter the behavior,
it is easy enough to do:

    try:
        return str(s)
    except UnicodeEncodeError:
        return unicode(s)


Raymond Hettinger




More information about the Python-list mailing list