Unreasonable output from codecs.decode()
<p>I have been playing around with the <code>codecs</code> module lately and I stumbled upon this behavior that I find rather weird:<br>
<code>codecs.encode(b'a', 'hex')</code> returns <code>b'61'</code>.</p>

<p>My question is, why? I really didn't expect it to return <code>b'61'</code>. I was expecting <code>b'\x61'</code>.<br>
The former is a <code>bytes</code> object with length 2 (<code>len(b'61') == 2</code>), whereas the latter one is a <code>bytes</code> object with length 1 (<code>len(b'\x61') == 1</code>).</p>

<p>I didn't expect this behavior at all, because <code>b'a'</code>, which is supposed to be 1-byte, has became 2-bytes when encoded with the <code>'hex'</code> codecs.</p>

<p>What would you have done to convert an ASCII character to its hex-encoded <code>bytes</code> representation? What I did was:</p>

<pre><code>codecs.decode(hex(ord('a'))[2:], 'hex')
</code></pre>

<p>But I felt like this is kind of a dirty hack.</p>

<p>The behaviour of codec is documented, the purpose is to make a text representation of (possibly) binary data. </p>

<p>If you want to convert a character 'a' to a bytes representation of that character using ascii, you don't need the codec module; just use the <code>bytes</code> builtin.</p>

<pre><code>&gt;&gt;&gt; bytes('a','ascii')
b'a'
</code></pre>

<p>As noted in the comments, b'a' is equal to b'\x61'</p>

python python-3.x encoding