title: Convert a string to literal type
body: <p>Can somebody help me how  can I convert a bytes string to a literal type, for example:</p>
  <pre><code>string = 'z\xff\xcaQ\x01\x9b\xe1\xe4\x85\xe4\x1c\xbb\x18yQf\xb0A\x89\xac\x89\x01I\xe2\xec\x06|\x1f\xcf9&quot;\xcf'
  </code></pre>
  <p>I want this string to be literal, then I have a function that converts it to  bytes:</p>
  <pre><code>literal_of_the_string = 'z\xff\xcaQ\x01\x9b\xe1\xe4\x85\xe4\x1c\xbb\x18yQf\xb0A\x89\xac\x89\x01I\xe2\xec\x06|\x1f\xcf9&quot;\xcf'
  
  bytes_of_literal = b 'z\xff\xcaQ\x01\x9b\xe1\xe4\x85\xe4\x1c\xbb\x18yQf\xb0A\x89\xac\x89\x01I\xe2\xec\x06|\x1f\xcf9&quot;\xcf' 
  </code></pre>
  <p>I tried with this:</p>
  <pre><code>import struct
  
  def convert_string_to_bytes(string):
  
      bytes = b''
      for i in string:
          bytes += struct.pack(&quot;B&quot;, ord(i))
      return bytes 
  </code></pre>
  <p>But the input must be literal to give me the right answer, I want answer like this:</p>
  <pre><code>bytes_of_literal = b 'z\xff\xcaQ\x01\x9b\xe1\xe4\x85\xe4\x1c\xbb\x18yQf\xb0A\x89\xac\x89\x01I\xe2\xec\x06|\x1f\xcf9&quot;\xcf'
  </code></pre>
  <p>but if I place the string for input, it will be something like this that is not the answer I need:</p>
  <pre><code>bad_answer =  b'I\\\x1f\\\xf6e5&gt;\\\x8f\\\x04\\\x87\\\xc2[\\\x96\\\x18\\\x7fs\\\xa5' 
  </code></pre>
  <p>The problem is the string is a variable in a program that I can't put &quot;r&quot; before string. How can I do this?</p>