title: (Python) Formatting strings for struct.unpack?
body: <p>I have a .csv file of values 0-255 that are simulating the data coming off an attitude sensor I'm looking at buying. I'm trying to write a data parser for it using this simulated data. The data will be transmitted over a serial port and packed into a byte array. I've looked into using struct.unpack to decode the data, and it makes sense to me, but I'm having trouble getting the data formatted correctly to run through struct.unpack. Here's an example:</p>
  
  <p>The year is packed as an unsigned short (2 hex values). "2014" would then be ('0xde', '0x07'). Converting to dec, this gives me ('222', '7'), which is what's in my csv file. The problem is, doing</p>
  
  <pre><code>hex(222)+hex(7)
  </code></pre>
  
  <p>gives me</p>
  
  <pre><code>'0xde0x7'
  </code></pre>
  
  <p>But I can't put that in here</p>
  
  <pre><code>unpack('H', '0xde0x7')
  </code></pre>
  
  <p>because it's formatted incorrectly. It needs to be</p>
  
  <pre><code>unpack('H', '\xde\x07')
  </code></pre>
  
  <p>Here's my current approach that's not working:</p>
  
  <pre><code>dataList = reader(open('testdata.csv', "rb"), delimiter = ",", skipinitialspace=True)
  dataList = [[eval(row[0])] for row in dataList]
  dataList = [hex(row[0]) for row in dataList]
  year = unpack('H', dataList[1]+dataList[2]))
  </code></pre>
  
  <p>Somehow I need to replace all the leading '0' with '\', then pad any number less than 15 (hex F) with a leading 0. Is there an elegant way to do this, or am I over-thinking it?</p>