title: How to print out 0xfb in python
body: <p>I'm falling the unicode hell.</p>
  
  <p>My environment in on unix, python 2.7.3</p>
  
  <pre><code>LC_CTYPE=zh_TW.UTF-8
  LANG=en_US.UTF-8
  </code></pre>
  
  <p>I'm trying to dump hex encoded data in human readable format, here is simplified code</p>
  
  <pre><code>#! /usr/bin/env python
  # encoding:utf-8
  import sys
  
  s=u"readable\n"  # previous result keep in unicode string
  s2="fb is not \xfb"  # data read from binary file
  s += s2
  
  print s   # method 1
  print s.encode('utf-8')  # method 2
  print s.encode('utf-8','ignore')  # method 3
  print s.decode('iso8859-1')  # method 4
  
  # method 1-4 display following error message
  #UnicodeDecodeError: 'ascii' codec can't decode byte 0xfb 
  # in position 0: ordinal not in range(128)
  
  f = open('out.txt','wb')
  f.write(s)
  </code></pre>
  
  <p>I just want to print out the 0xfb.</p>
  
  <p>I should describe more here. The key is 's += s2'.
  Where s will keep my previous decoded string.
  And the s2 is next string which should append into s.</p>
  
  <p>If I modified as following, it occurs on write file.</p>
  
  <pre><code>s=u"readable\n"
  s2="fb is not \xfb"
  s += s2.decode('cp437')
  print s
  f=open('out.txt','wb')
  f.write(s)
  # UnicodeEncodeError: 'ascii' codec can't encode character
  # u'\u221a' in position 1: ordinal not in range(128)
  </code></pre>
  
  <p>I wish the result of out.txt is</p>
  
  <pre><code>readable
  fb is not \xfb
  </code></pre>
  
  <p>or</p>
  
  <pre><code>readable
  fb is not 0xfb
  </code></pre>
  
  <p>[Solution]</p>
  
  <pre><code>#! /usr/bin/env python
  # encoding:utf-8
  import sys
  import binascii
  
  def fmtstr(s):
      r = ''
      for c in s:
          if ord(c) &gt; 128:
              r = ''.join([r, "\\x"+binascii.hexlify(c)])
          else:
              r = ''.join([r, c])
      return r
  
  s=u"readable"
  s2="fb is not \xfb"
  s += fmtstr(s2)
  print s
  f=open('out.txt','wb')
  f.write(s)
  </code></pre>