.format vs. %
Neil Cerutti
neilc at norwich.edu
Tue Jan 3 14:46:40 EST 2012
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
--
Neil Cerutti
More information about the Python-list
mailing list