Python 2.6 introduced the str.format() method with a slightly different syntax from the existing %
operator. Which is better and for what situations?
Pyt
%
gives better performance than format
from my test.
Test code:
Python 2.7.2:
import timeit
print 'format:', timeit.timeit("'{}{}{}'.format(1, 1.23, 'hello')")
print '%:', timeit.timeit("'%s%s%s' % (1, 1.23, 'hello')")
Result:
> format: 0.470329046249
> %: 0.357107877731
Python 3.5.2
import timeit
print('format:', timeit.timeit("'{}{}{}'.format(1, 1.23, 'hello')"))
print('%:', timeit.timeit("'%s%s%s' % (1, 1.23, 'hello')"))
Result
> format: 0.5864730989560485
> %: 0.013593495357781649
It looks in Python2, the difference is small whereas in Python3, %
is much faster than format
.
Thanks @Chris Cogdon for the sample code.
Edit 1:
Tested again in Python 3.7.2 in July 2019.
Result:
> format: 0.86600608
> %: 0.630180146
There is not much difference. I guess Python is improving gradually.
Edit 2:
After someone mentioned python 3's f-string in comment, I did a test for the following code under python 3.7.2 :
import timeit
print('format:', timeit.timeit("'{}{}{}'.format(1, 1.23, 'hello')"))
print('%:', timeit.timeit("'%s%s%s' % (1, 1.23, 'hello')"))
print('f-string:', timeit.timeit("f'{1}{1.23}{\"hello\"}'"))
Result:
format: 0.8331376779999999
%: 0.6314778750000001
f-string: 0.766649943
It seems f-string is still slower than %
but better than format
.