Reputation: 3966
When converting an object to a string in python, I saw two different idioms:
A: mystring = str(obj)
B: mystring = "%s" % obj
Is there a difference between those two? (Reading the Python docs, I would suspect no, because the latter case would implicitly call str(obj)
to convert obj
to a string.
If yes, when should I use which?
If no, which one should I prefer in "good" python code? (From the python philosophy "explicit over implicit", A would be considered the better one?)
Upvotes: 10
Views: 379
Reputation: 1123400
The second version does more work.
The %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.
Upvotes: 17