.format vs. %

Joshua Landau joshua.landau.ws at gmail.com
Tue Jan 3 15:04:34 EST 2012


On 3 January 2012 19:46, Neil Cerutti <neilc at norwich.edu> wrote:

> On 2012-01-03, Stefan Krah <stefan-usenet at bytereef.org> wrote:
> > Andrew Berg <bahamutzero8825 at gmail.com> wrote:
> >> To add my opinion on it, I find format() much more readable and easier
> >> to understand (with the exception of the {} {} {} {} syntax), and would
> >> love to see %-style formatting phased out.
> >
> > For me the %-style is much more readable. Also, it is significantly
> > faster:
> >
> > $ ./python -m timeit -n 1000000 '"%s" % 7.928137192'
> > 1000000 loops, best of 3: 0.0164 usec per loop
>
> I have done a little more investigating, and the above is
> arguably not fair. Python is interpolating that string at compile
> time, as far as I can tell. Pretty cool, and not possible with
> .format, but it's just regurgitating a string literal over and
> over, which isn't of much interest.
>
> % is faster, but not by an order of magnitude.
>
> On my machine:
>
> C:\WINDOWS>python -m timeit -n 1000000 -s "n=7.92" "'%s' % n"
> 1000000 loops, best of 3: 0.965 usec per loop
>
> C:\WINDOWS>python -m timeit -n 1000000 -s "n=7.92" "'{}'.format(n)"
> 1000000 loops, best of 3: 1.17 usec per loop


Cool! And you can make up half the difference, too:

%~> python -m timeit -n 1000000 -s "n=7.92" "'%s' % n"
1000000 loops, best of 3: 1.27 usec per loop
%~> python -m timeit -n 1000000 -s "n=7.92" "'{}'.format(n)"
1000000 loops, best of 3: 1.81 usec per loop
%~> python -m timeit -n 1000000 -s "n=7.92; x='{}'.format" "x(n)"
1000000 loops, best of 3: 1.51 usec per loop
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20120103/518c1d11/attachment.html>


More information about the Python-list mailing list