Although you've accepted my other answer, after noticing your comment explaining that what you really wanted was to convert the data into binary using struct.pack(), I've written another that might suit you even better (despite being longer and a little more complicated).
import struct
class TypeConv(object):
BSA = '=' # native Byte order, standard Size, with no Alignment
def __init__(self, conv_func, fmt_chr):
self.__dict__.update(conv_func=conv_func, fmt_chr=fmt_chr)
def pack(self, data):
py_value = self.conv_func(data)
count = str(len(py_value)) if self.conv_func is str else ''
return struct.pack(self.BSA+count+self.fmt_chr, py_value)
type_conv = {'string': TypeConv(str, 's'),
'int32': TypeConv(int, 'i'),
'int64': TypeConv(long, 'q'),
'float32': TypeConv(float, 'f'),
}
array = [['string', 'int32', 'string', 'int64', 'float32', 'string', 'string'],
['any string', '19', 'any string', '198732132451654654',
'0.6', 'any string', 'any string']]
binary_values = [type_conv[type_id].pack(data)
for type_id, data in zip(array[0], array[1])
if type_id in type_conv] # to skip any unknown type_ids
print binary_values
Output:
['any string', '\x13\x00\x00\x00', 'any string', '\xfe\x9b<P\xd2\t\xc2\x02',
'\x9a\x99\x19?', 'any string', 'any string']
The TypeConv.pack() method first converts the string value to its equivalent Python value py_value, then uses struct.pack() to convert that to a C binary value -- which I think is what you seek.