String formatting char

Kragen Sitaker kragen at canonical.org
Wed Nov 21 15:38:55 EST 2001


Dale Strickland-Clark <dale at riverhall.NOTHANKS.co.uk> writes:
> "Daniel Dittmar" <daniel.dittmar at sap.com> 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'})
1.4125577446059787e-05
>>> import re
>>> myre = re.compile(r'%\(([^)]+)\)s')
>>> Speed.seconds_per_call(lambda: myre.sub(lambda match: {'silly': 'orange'}[match.group(1)], "This is a %(silly)s string for happiness"))
0.00017021971215807361

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