Python 2.6 introduced the str.format() method for formatting strings which provides a much more flexible alternative to the older modulo (%) based string formatting. But which one performs better? Let's test it out by repeating a simple string format a million times with each method and timing the execution.1
str.format vs. (%) modulo
from timeit import timeit
def test_modulo():
'Don\'t %s, I\'m the %s.' % ('worry', 'Doctor')
def test_format():
'Don\'t {0}, I\'m the {1}.'.format('worry', 'Doctor')
timeit(stmt=test_modulo, number=1000000)
# 0.31221508979797363
timeit(stmt=test_format, number=1000000)
# 0.5489029884338379
Hmmm, the modulo operator is almost twice as fast as str.format() in these simple examples.
In cases where you don't require the flexibility of str.format() and simply want sheer perfomance... Modulo has got to be the way to go... But according to PEP-3101, str.format() is intended to replace the modulo operator... Let's hope that doesn't happen anytime soon.
Template strings
For completeness, Python also supports string templates (introduced in Python 2.4). Let's put that to the test.
from string import Template
s = Template('Don\'t $what, I\'m the $who.')
def test_template():
s.substitute(what='worry', who='Doctor')
timeit(stmt=test_template, number=1000000)
# 6.010946035385132
Ouch!
Update: 5/12/2017:
Python 3.6 introduced f-strings which provide a new method of string formatting. Let's see how f-strings perform...
from timeit import timeit
def test_fstring():
a, b = 'worry', 'Doctor'
f'Don\'t {a}, I\'m the {b}.'
timeit(stmt=test_fstring, number=1000000)
# 0.276932206004858
Well, there we have it... f-strings combine the elegance of .format(), yet is slightly faster than the modulo operator. Big thanks to @StopSpazzing for pointing this out.
-
Tests were performed on a MacBook Pro (2.4 Ghz Intel Core i7) and Python 2.7.2. With Spotify playing the Melvins in the background. ↩