When converting an object to a string in python, I saw two different idioms:
mystring = str(obj)
mystring = "%s" % obj
The second version does more work.
%s operator calls
str() on the value it interpolates, but it also has to parse the template string first to find the placeholder in the first place.
Unless your template string contains more text, there is no point in asking Python to spend more cycles on the
"%s" % obj expression.
However, paradoxically, the
str() conversion is, in practice, slower as looking up the name
str() and pushing the stack to call the function takes more time than the string parsing:
>>> from timeit import timeit >>> timeit('str(obj)', 'obj = 4.524') 0.32349491119384766 >>> timeit('"%s" % obj', 'obj = 4.524') 0.27424097061157227
You can recover most of that difference by binding
str to a local name first:
>>> timeit('_str(obj)', 'obj = 4.524; _str = str') 0.28351712226867676
To most Python developers, using the string templating option is going to be confusing as
str() is far more straightforward. Stick to the function unless you have a critical section that does a lot of string conversions.