Python3 change string to byte
<p>I'm using Python3.5 and I want to change <code>\xe1BA\x06\xbe\x084</code> into <code>b'\xe1BA\x06\xbe\x084'</code></p>

<p>But using <code>'\xe1BA\x06\xbe\x084'.encode('ascii')</code> or <code>'\xe1BA\x06\xbe\x084'.encode('utf-8')</code>doesn't work.</p>

<p>In <code>.encode('utf-8')</code>, it will become<br>
<code>b'\xc3\xa1BA\x06\xc2\xbe\x084'</code>  differs from<br>
<code>b'\xe1BA\x06\xbe\x084'</code></p>

<p>How to deal with this?</p>

<p>Use the <code>latin1</code> codec.</p>

<pre><code>&gt;&gt;&gt; '\xe1BA\x06\xbe\x084'.encode('latin1')
b'\xe1BA\x06\xbe\x084'
</code></pre>

<p>The reason why this works (and is the way it is) because originally those bytes sequences were defined to be those characters by the <a href="https://en.wikipedia.org/wiki/ISO/IEC_8859-1" rel="nofollow">ISO-8859-1 standard</a>, and thus encoding them down back using that encoding well, gets you back those exact bytes.</p>

<p>While the other answer is useful (the loop through all available codecs to get all possible output is great), do keep in mind that while other specific codecs will work for some specific strings, it may or may not end up mapping to the identical base "byte" sequence.</p>

<pre><code>&gt;&gt;&gt; '\xfe'.encode('iso8859_9')
Traceback (most recent call last):
  File "&lt;stdin&gt;", line 1, in &lt;module&gt;
  File "/usr/lib/python3.5/encodings/iso8859_9.py", line 12, in encode
    return codecs.charmap_encode(input,errors,encoding_table)
UnicodeEncodeError: 'charmap' codec can't encode character '\xfe' in position 0: character maps to &lt;undefined&gt;
&gt;&gt;&gt; '\xfe'.encode('latin1')
b'\xfe'
&gt;&gt;&gt; 
</code></pre>

<p>Of course, the <code>raw_unicode_escape</code> can be useful if your intent is to encode everything to a form of base byte encoding that also allow anything > <code>\xff</code> to be represented through the <code>\\uXXXX</code> form:</p>

<pre><code>&gt;&gt;&gt; 'ã'.encode('latin1')
Traceback (most recent call last):
  File "&lt;stdin&gt;", line 1, in &lt;module&gt;
UnicodeEncodeError: 'latin-1' codec can't encode character '\u3042' in position 0: ordinal not in range(256)
&gt;&gt;&gt; 'ã'.encode('raw_unicode_escape')
b'\\u3042'
&gt;&gt;&gt; 
</code></pre>

<p>Naturally, pick the strategy that makes the most sense for your intent.</p>

python unicode utf-8