title: Converting Byte to String and Back Properly in Python3?
body: <p>Given a random byte (i.e. not only numbers/characters!), I need to <strong>convert it to a string</strong> and then <strong>back to the inital byte</strong> without loosing information. This seems like a basic task, but I ran in to the following problems:</p>
  
  <p>Assuming:</p>
  
  <pre><code>rnd_bytes = b'w\x12\x96\xb8'
  len(rnd_bytes)
  </code></pre>
  
  <p>prints: <code>4</code></p>
  
  <p>Now, converting it to a string. Note: I need to set <code>backslashreplace</code> as it otherwise returns a 'UnicodeDecodeError' or would loose information setting it to another flag value.</p>
  
  <pre><code>my_str = rnd_bytes.decode('utf-8' , 'backslashreplace')
  </code></pre>
  
  <p>Now, I have the string. 
  I want to convert it back to exactly the original byte (size 4!):</p>
  
  <p>According to  python ressources and this <a href="https://stackoverflow.com/questions/7585435/best-way-to-convert-string-to-bytes-in-python-3">answer</a>, there are different possibilities:</p>
  
  <pre><code>conv_bytes = bytes(my_str, 'utf-8')
  conv_bytes = my_str.encode('utf-8')
  </code></pre>
  
  <p>But len(conv_bytes) returns <code>10</code>. </p>
  
  <p>I tried to analyse the outcome:</p>
  
  <pre><code>&gt;&gt;&gt; repr(rnd_bytes)
  "b'w\\x12\\x96\\xb8'"
  &gt;&gt;&gt; repr(my_str)
  "'w\\x12\\\\x96\\\\xb8'"
  &gt;&gt;&gt; repr(conv_bytes)
  "b'w\\x12\\\\x96\\\\xb8'"
  </code></pre>
  
  <p>It would make sense to replace <code>'\\\\'</code>. <code>my_str.replace('\\\\','\\')</code> doesn't change anything. Probably, because four backslashes represent only two. So, <code>my_str.replace('\\','\')</code> would find the <code>'\\\\'</code>, but leads to</p>
  
  <blockquote>
    <p>SyntaxError: EOL while scanning string literal</p>
  </blockquote>
  
  <p>due to the last argument <code>'\'</code>. This had been discussed <a href="https://stackoverflow.com/a/14453186/4673476">here</a>, where the following suggestion came up:</p>
  
  <pre><code>&gt;&gt;&gt; my_str2=my_str.encode('utf_8').decode('unicode_escape')
  &gt;&gt;&gt; repr(my_str2)
  "'w\\x12\\x96¸'"
  </code></pre>
  
  <p>This replaces the <code>'\\\\'</code> but seems to add / change some other characters:</p>
  
  <pre><code>&gt;&gt;&gt; conv_bytes2 = my_str2.encode('utf8')
  &gt;&gt;&gt; len(conv_bytes2)
  6
  &gt;&gt;&gt; repr(conv_bytes2)
  "b'w\\x12\\xc2\\x96\\xc2\\xb8'"
  </code></pre>
  
  <p>There <em>must</em> be a prober way to convert a (complex) byte to a string and back. How can I achieve that?</p>