.format vs. %

Neil Cerutti neilc at norwich.edu
Tue Jan 3 08:58:21 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
> $ ./python -m timeit -n 1000000 '"{}".format(7.928137192)'
> 1000000 loops, best of 3: 1.01 usec per loop
>
> In the real-world telco benchmark for _decimal, replacing the
> single line
>
>     outfil.write("%s\n" % t)
>
> with
>
>     outfil.write("{}\n".format(t))
>
> adds 23% to the runtime. I think %-style formatting should not
> be deprecated at all.
   
When it becomes necessary, it's possible to optimize it by
hoisting out the name lookups.
   ...
   outfil_write = outfil.write
   append_newline = "{}\n".format
   ...
       outfil_write(append_newline(t))
       ...

-- 
Neil Cerutti



More information about the Python-list mailing list