title: What is a Python bytestring?
body: <p>What's a Python bytestring?</p>
  <p>All I can find are topics on how to encode to bytestring or decode to <a href="https://en.wikipedia.org/wiki/ASCII" rel="nofollow noreferrer">ASCII</a> or <a href="https://en.wikipedia.org/wiki/UTF-8" rel="nofollow noreferrer">UTF-8</a>. I'm trying to understand how it works under the hood. In a normal ASCII string, it's an array or list of characters, and each character represents an ASCII value from 0-255, so that's how you know what character is represented by the number. In Unicode, it's the 8- or 16-byte representation for the character that tells you what character it is.</p>
  <p>So what is a bytestring? How does Python know which characters to represent as what? How does it work under the hood? Since you can print or even return these strings and it shows you the string representation, I don't quite get it...</p>
  <p>Ok, so my point is <em>definitely</em> getting missed here. I've been told that it's an <em>immutable</em> sequence of bytes without any particular <em>interpretation</em>.</p>
  <p>A sequence of bytes.. Okay, let's say one byte:
  <code>'a'.encode()</code> returns <code>b'a'</code>.</p>
  <p>Simple enough. Why can I read the <strong>a</strong>?</p>
  <p>Say I get the ASCII value for <strong>a</strong>, by doing this:
  <code>printf &quot;%d&quot; &quot;'a&quot;</code></p>
  <p>It returns <strong>97</strong>. Okay, good, the integer value for the ASCII character <strong>a</strong>. If we interpret <strong>97</strong> as ASCII, say in a C <code>char</code>, then we get the letter <code>a</code>. Fair enough. If we convert the byte representation to bits, we get this:</p>
  <p><code>01100001</code></p>
  <p><em>2^0 + 2^5 + 2^6 = 97</em>. Cool.</p>
  <p>So why is <code>'a'.encode()</code> returning <code>b'a'</code> instead of <code>01100001</code>?? <br />
  If it's <strong>without</strong> a particular <em>interpretation</em>, shouldn't it be returning something like <code>b'01100001'</code>? <br />
  It <strong>seems</strong> like it's interpreting it like ASCII.</p>
  <p>Someone mentioned that it's calling <code>__repr__</code> on the bytestring, so it's displayed in human-readable form. However, even if I do something like:</p>
  <pre><code>with open('testbytestring.txt', 'wb') as f:
      f.write(b'helloworld')
  </code></pre>
  <p>It will <em>still</em> insert <code>helloworld</code> as a regular string into the file, not as a sequence of bytes... So is a bytestring in ASCII?</p>