Is there any way in python to add extra conversion types to string formatting?
The standard conversion types used in % -based formatting are strings such as s for strings, d for decimals, etc. What I would like to do is add a new character for which I can specify a custom handler (for example, a lambda function) that will return a string to be inserted.
For example, I would like to add h as a conversion type to indicate that the string should be escaped for use in HTML. As an example:
#!/usr/bin/python print "<title>%(TITLE)h</title>" % {"TITLE": "Proof that 12 < 6"}
And this will use cgi.escape on "TITLE" to create the following output:
<title>Proof that 12 < 6</title>
python printf string-formatting
brianmearns
source share