title: How can I generate \x-escaped UTF-8 in Python?
body: <p>I want to convert a unicode input to a \x escaped, 7-bit-ascii-clean reprentation of a UTF-8 byte sequence.</p>
  
  <p>This is analogous to what I need, but instead of <code>"\u222a"</code> I would like to generate <code>"\xe2\x88\xaa"</code></p>
  
  <pre><code>&gt;&gt;&gt; codecs.encode(u"\u222A", 'ascii', 'backslashreplace')
  '\\u222a'
  </code></pre>
  
  <p>This looks like it is generating the desired result:</p>
  
  <pre><code>&gt;&gt;&gt; u"\u222A".encode('utf-8')
  '\xe2\x88\xaa'
  </code></pre>
  
  <p>But that is merely an escaped representation. The actual result isn't 12 ascii bytes, it's 3 UTF-8 bytes:</p>
  
  <pre><code>&gt;&gt;&gt; [ord(c) for c in u"\u222A".encode('utf-8')]
  [226, 136, 170]
  </code></pre>
  
  <p>I could abuse that escaped representation to get what I want, stripping off the leading and trailing quote that repr adds:</p>
  
  <pre><code>&gt;&gt;&gt; repr(u"\u222A".encode('utf-8'))[1:-1]
  '\\xe2\\x88\\xaa'
  &gt;&gt;&gt; [ord(c) for c in repr(u"\u222A".encode('utf-8'))[1:-1]]
  [92, 120, 101, 50, 92, 120, 56, 56, 92, 120, 97, 97]
  </code></pre>
  
  <p>Yuck. This is a little better:</p>
  
  <pre><code>&gt;&gt;&gt; import binascii
  &gt;&gt;&gt; ''.join('\\x' + binascii.hexlify(c) for c in u"\u222A".encode('utf-8'))
  '\\xe2\\x88\\xaa'
  &gt;&gt;&gt; [ord(c) for c in ''.join('\\x' + binascii.hexlify(c) for c in u"\u222A".encode('utf-8'))]
  [92, 120, 101, 50, 92, 120, 56, 56, 92, 120, 97, 97]
  </code></pre>
  
  <p>Is a better way to do this?</p>