Python: convert string to packed hex ( '01020304' -> '\x01\x02\x03\x04' )
<p>I'm trying to convert a string of numbers into a 'packed hex' format.</p>

<p>For example: '01020304' -> '\x01\x02\x03\x04'</p>

<p>I have it working, but I expect there are better (faster, cleaner) more pythonic ways to do this?</p>

<pre><code>def split_len(seq, length):
    return [seq[i:i+length] for i in range(0, len(seq), length)]

def ascii_to_packed_hex(string_data): 
    r"""
    &gt;&gt;&gt; ascii_to_packed_hex('01')
    '\x01'

    &gt;&gt;&gt; ascii_to_packed_hex('0102030405')
    '\x01\x02\x03\x04\x05'

    &gt;&gt;&gt; ascii_to_packed_hex('fafbfcfd')
    '\xfa\xfb\xfc\xfd'

    &gt;&gt;&gt; ascii_to_packed_hex('31323334')
    '1234'
    """               
    hex_data=''
    string_data = string_data.encode('iso-8859-1')
    string_parts = split_len(string_data, 2)

    if len(string_parts)&gt;=1:
        for each_part in string_parts:
            encoded_part = each_part[:2]
            ascii_part   = each_part[2:]
            encoded_part_as_hex = string.atoi(encoded_part,base=16)
            encoded_part_as_hex = chr(encoded_part_as_hex)
            hex_data = hex_data + encoded_part_as_hex + ascii_part
        return hex_data
    else:
        return string_data

    import doctest
    doctest.testmod()
</code></pre>
