Jan 132016
 

A search for information on string interpolation in Python will inevitably lead you to comments and links to old documentation that the string modulo operator is going to be deprecated and removed. However, that is just outright FUD. I need not make a case for the modulo operator, I’ll just let the code do the talking.

from timeit import timeit

def test_modulo():
    'Don\'t %s, I\'m the %s.' % ('worry', 'Doctor')

def test_format_explicit():
    'Don\'t {0}, I\'m the {1}.'.format('worry', 'Doctor')

def test_format_implicit():
    'Don\'t {}, I\'m the {}.'.format('worry', 'Doctor')

timeit(stmt=test_modulo, number=1000000)
timeit(stmt=test_format_explicit, number=1000000)
timeit(stmt=test_format_implicit, number=1000000)

Running the code on python 3.4.3 I get the following results:

>>> timeit(stmt=test_modulo, number=1000000)
0.668234416982159
>>> timeit(stmt=test_format_explicit, number=1000000)
0.9450872899033129
>>> timeit(stmt=test_format_implicit, number=1000000)
0.8761067320592701

Note that test_format_explicit is the form most commonly found on the web. However, the implicit version is a much closer equivalent to test_modulo. In this case, there is an apparent price for being explicit.

Until .format is on par, speed-wise, with % there is no chance of it being deprecated. I support .format‘s existance, in some battle grounds it is superior. You shouldn’t bring regex‘s to the fight when .starstwith, .find, .endswith or in can handle the challenge cleanly. The same is True for .format and %.

An as PEP 461 demonstrates, the string modulo operator is not going quietly into the night.

This post was inspired by curiosity after reading this 2013 article.

 Posted by at 3:14 am

  3 Responses to “string modulo vs. Format – Fight!”

  1. I’m eagerly waiting for f-strings ( https://www.python.org/dev/peps/pep-0498/ )..

  2. While I appreciate the desire for efficiency, consider a different perspective: over a million repetitions, percent substitution is faster than even explicit .format() by less than a third of a second. Given that, you’ve spent more time writing this post than you could ever possibly gain by using percent substitution. 🙂

    • You say that as if it were a bad thing. The point being is that the older interpolation method is faster than the new so there is little reason to modify old code or even write new code using .format if it isn’t specifically needed. Hence my argument that % is not going away anytime soon.

Sorry, the comment form is closed at this time.