title: Python: How to turn a string of binary values (arbitrary length) into hex data?
body: <p>I need to turn a string like <code>data = "00000111010110101"</code> into a hex string, in this example I need '075A80'</p>
  
  <p>You may notice a few caveats:</p>
  
  <ul>
  <li>leading zeros should not be stripped so hex(int(data,2)) doesn't work for me</li>
  <li>if len(data) %8 != 0 the string should be appended with zeros to end with a full byte</li>
  </ul>
  
  <p>After searching this forum and hacking together different answers, this is one way I found to do it, but it seems rather complex and I hope someone else sees a much simpler way.</p>
  
  <pre><code>data_hex = "".join([ "%02X" % int("".join(a),2) for a in izip_longest(*(iter(data),)*8, fillvalue='0')])
  </code></pre>
  
  <p>Thanks!</p>
  
  <p>Edit: Some background on the data. The underlying data is purely bits, it does not represent an integer or other numeric value, so the leading zeros are relevant and must be represented in the result. Also appending zeros at the (right) end doesn't change the "value" in my use case.</p>