title: Detect the type of strings
body: <p>I want to create a python script that uses strings in byte format that can be written to a file.</p>
  
  <p>So the problem is something like this:</p>
  
  <pre><code>packed_int = struct.pack('&gt;I', 1234)
  result = packed_int + data
  </code></pre>
  
  <p>Here is the problem: In python 3 this will give an error because of concatenation between str and bytes.</p>
  
  <p>So I solved the problem with the following code:</p>
  
  <pre><code>data = data.encode('utf-8')
  packed_int = struct.pack('&gt;I', 1234)
  result = packed_int + data
  </code></pre>
  
  <p>Now if the data is already in bytes format this will give an error of not having an encode method. So I did this:</p>
  
  <pre><code>if type(data) is not bytes:
      data = data.encode('utf-8')
  </code></pre>
  
  <p>The final problem is the fact that in python 2 the last snippet does not work. </p>
  
  <p>How can I solve the problem without checking for python version?  </p>