String formatting char

Kragen Sitaker kragen at
Wed Nov 21 21:38:55 CET 2001

Dale Strickland-Clark <dale at> writes:
> "Daniel Dittmar" <daniel.dittmar at> wrote:
> >The %(varname)s formatting can be implemented using the re.sub method:
> That's neat and gives you complete flexibility over the the
> substitution syntax - you could use !var!, for example but assumes a
> string substition.
> Also it would be much slower than the built-in function.

It is indeed slower; whether this matters or not for your application
is something you should think about.  How many times are you doing %
on how many different format strings and how fast does your
application currently run?  My benchmarking:

Python 2.1.1 (#1, Oct 24 2001, 10:59:24) 
[GCC 2.95.2 20000220 (Debian GNU/Linux)] on linux2
Type "copyright", "credits" or "license" for more information.
>>> import Speed
>>> Speed.seconds_per_call(lambda: "This is a %(silly)s string for happiness" %  {'silly': 'orange'})
>>> import re
>>> myre = re.compile(r'%\(([^)]+)\)s')
>>> Speed.seconds_per_call(lambda: myre.sub(lambda match: {'silly': 'orange'}[], "This is a %(silly)s string for happiness"))

So there you have it: 170 microseconds for re.sub, 14 microseconds for
builtin %.

I think the other complaint, namely that you don't get all of printf's
flexibility (to do %d, %f, %20.30s, etc.) is more significant.

More information about the Python-list mailing list