title: What does python print() function actually do?
body: <p>I was looking at this <a href="https://stackoverflow.com/questions/1979171/how-can-i-escape-xff-xfe-to-a-readable-string">question</a> and started wondering what does the <code>print</code> actually do.</p>
  
  <p>I have never found out how to use <code>string.decode()</code> and <code>string.encode()</code> to get an unicode string "out" in the python interactive shell in the same format as the print does. No matter what I do, I get either</p>
  
  <ol>
  <li>UnicodeEncodeError or </li>
  <li>the escaped string with "\x##" notation...</li>
  </ol>
  
  <p>This is python 2.x, but I'm already trying to mend my ways and actually call <code>print()</code> :)</p>
  
  <p>Example:</p>
  
  <pre><code>&gt;&gt;&gt; import sys
  &gt;&gt;&gt; a = '\xAA\xBB\xCC'
  &gt;&gt;&gt; print(a)
  ª»Ì
  &gt;&gt;&gt; a.encode(sys.stdout.encoding)
  Traceback (most recent call last):
    File "&lt;stdin&gt;", line 1, in ?
  UnicodeDecodeError: 'ascii' codec can't decode byte 0xaa in position 0: ordinal not in range(128)
  &gt;&gt;&gt; a.decode(sys.stdout.encoding)
  u'\xaa\xbb\xcc'
  </code></pre>
  
  <p><strong>EDIT</strong>:</p>
  
  <p>Why am I asking this? I am sick and tired of <code>encode()</code> errors and realized that since <code>print</code> can do it (at least in the interactive shell). I know that the <strong>MUST BE A WAY</strong> to magically do the encoding <strong>PROPERLY</strong>, by digging the info what encoding to use from somewhere...</p>
  
  <p><strong>ADDITIONAL INFO</strong>:
  I'm running Python 2.4.3 (#1, Sep  3 2009, 15:37:12) [GCC 4.1.2 20080704 (Red Hat 4.1.2-46)] on linux2</p>
  
  <pre><code>&gt;&gt;&gt; sys.stdin.encoding
  'ISO-8859-1'
  &gt;&gt;&gt; sys.stdout.encoding
  'ISO-8859-1'
  </code></pre>
  
  <p>However, the results are the same with Python 2.6.2 (r262:71600, Sep  8 2009, 13:06:43) on the same linux box.</p>