Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<blockquote> <p>why did the last line get the correct output, and the others didn't?</p> </blockquote> <p>When you <code>print foo</code>, what gets printed out is <code>str(foo)</code>.</p> <p>However, if <code>foo</code> is a <code>list</code>, <code>str(foo)</code> uses <code>repr(bar)</code> for each element <code>bar</code>, not <code>str(bar)</code>.</p> <p>The <code>str</code> of a string is the string itself; the <code>repr</code> of a string is the string inside quotes, and escaped.</p> <blockquote> <p>how do I correct the wrong ones</p> </blockquote> <p>If you want to print the <code>str</code> of every element in a <code>list</code>, you have to do that explicitly. For example:</p> <pre><code>print '[' + ', '.join(["asdf", "中文"]) + ']' </code></pre> <hr> <p>There have been sporadic proposals to change this behavior, so <code>str</code> on a sequence calls <code>str</code> on its members. <a href="http://www.python.org/dev/peps/pep-3140/" rel="nofollow">PEP 3140</a> is the rejected proposal. <a href="http://code.activestate.com/lists/python-ideas/20009/" rel="nofollow">This thread from 2009</a> explains the design rationale behind rejecting it. </p> <p>But primarily, it's either so these don't print the same thing:</p> <pre><code>a = 'foo, bar' b = 'foo' c = 'bar' print [a] print [b, c] </code></pre> <p>Or, paraphrasing Ned Batchelder: <code>repr</code> is always for geeks; <code>str</code> is for humans when possible, but printing lists with their brackets and commas is already for geeks.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload