Stefan Winkler Stefan Winkler - 6 months ago 36
Python Question

Is there a difference between str function and percent operator in Python

When converting an object to a string in python, I saw two different idioms:


mystring = str(obj)

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
to convert
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?)


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')
>>> timeit('"%s" % obj', 'obj = 4.524')

You can recover most of that difference by binding str to a local name first:

>>> timeit('_str(obj)', 'obj = 4.524; _str = str')

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.