Quantcast
Channel: Planet Python
Viewing all articles
Browse latest Browse all 22462

Jeff Hinrichs: string modulo vs. Format – Fight!

$
0
0

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.


Viewing all articles
Browse latest Browse all 22462

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>