Hexadecimal: how to convert 'ED6F3C01' to "\xED\x6F\x3C\x01" in python coding?

John Machin sjmachin at lexicon.net
Sat May 24 19:28:55 EDT 2008


zxo102 wrote:
> Hi,
>    how  to change the hexadecimal 'ED6F3C01' (or 'ED 6F 3C 01') to
> "\xED\x6F\x3C\x01" in python coding?

If by "in python coding" you mean "in Python source code", then just 
type it in with \x in front of each pair of hex digits, like you did above.

However if you mean e.g. how to change a data string x into a data 
string y, something like this is what you want

 >>> import binascii
 >>> x = 'ED 6F 3C 01'
 >>> y = binascii.unhexlify(x.replace(' ', ''))
 >>> y
'\xedo<\x01'

... which is correct ('o' == '\x6f' and '<' == '\x3c'); see below:

 >>> ' '.join(['%02x' % ord(c) for c in y])
'ed 6f 3c 01'
 >>>> len(y)
4

Does (len(y) == 4) surprise you?

> When I take 'ED6F3C01' as a string and insert '\x' into it, I just got
> the error information : invalid \x escape.

It's rather difficult to guess what you mean here ... insert how many 
'\x'? where?? what gave you the error information??? Consider showing us 
a copy/paste of exactly what you did and what was the response, like I 
did above.


HTH,
John



More information about the Python-list mailing list