.format vs. %
Stefan Krah
stefan-usenet at bytereef.org
Tue Jan 3 15:53:14 EST 2012
Neil Cerutti <neilc at norwich.edu> wrote:
> On 2012-01-03, Stefan Krah <stefan-usenet at bytereef.org> wrote:
> > $ ./python -m timeit -n 1000000 '"%s" % 7.928137192'
> > 1000000 loops, best of 3: 0.0164 usec per loop
>
> % 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
Indeed, I was a bit surprised by the magnitude of the difference.
Your timings seem to be in line with the difference seen in the
real-world benchmark. It isn't a big deal, considering that the
numeric formatting functions have to so many options, e.g:
>>> "{:020,}".format(712312312.2)
'00,000,712,312,312.2'
Still, it's nice to have a faster choice.
Stefan Krah
More information about the Python-list
mailing list