Is there a difference between str function and percent operator in Python
<p>When converting an object to a string in python, I saw two different idioms:</p>

<p>A: <code>mystring = str(obj)</code></p>

<p>B: <code>mystring = "%s" % obj</code></p>

<p>Is there a difference between those two? (Reading the Python docs, I would suspect no, because the latter case would implicitly call <code>str(obj)</code> to convert <code>obj</code> to a string.</p>

<p>If yes, when should I use which? </p>

<p>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?)</p>

<p>The second version does more work.</p>

<p>The <code>%s</code> operator calls <code>str()</code> on the value it interpolates, but it also has to parse the template string first to find the placeholder in the first place.</p>

<p>Unless your template string contains <em>more text</em>, there is no point in asking Python to spend more cycles on the <code>"%s" % obj</code> expression.</p>

<p>However, paradoxically, the <code>str()</code> conversion is, in practice, slower as looking up the name <code>str()</code> and pushing the stack to call the function takes more time than the string parsing:</p>

<pre><code>&gt;&gt;&gt; from timeit import timeit
&gt;&gt;&gt; timeit('str(obj)', 'obj = 4.524')
0.32349491119384766
&gt;&gt;&gt; timeit('"%s" % obj', 'obj = 4.524')
0.27424097061157227
</code></pre>

<p>You can recover most of that difference by binding <code>str</code> to a local name first:</p>

<pre><code>&gt;&gt;&gt; timeit('_str(obj)', 'obj = 4.524; _str = str')
0.28351712226867676
</code></pre>

<p>To most Python developers, using the string templating option is going to be confusing as <code>str()</code> is far more straightforward. Stick to the function unless you have a critical section that does a lot of string conversions.</p>

python python-2.7