newbie string conversion question
Felipe Almeida Lessa
felipe.lessa at gmail.com
Sat Apr 1 09:33:16 EST 2006
Em Sáb, 2006-04-01 às 06:17 -0800, Rohit escreveu:
> As part of a proprietary socket based protocol I have to convert a
> string of length 10,
>
> say, "1234567890"
>
> to send it as 5 characters such that their hex values are
>
> 0x21 0x43 0x65 0x87 0x09
>
> (Hex value of each character is got by transposing two digits at a
> time)
>
> How can I do this in python? I would like the result to be available
> as a string since I am concatenating it to another string before
> sending it out.
You mean:
>>> a = "1234567890"
>>> b = []
>>> for i in range(len(a)/2):
... b.append(chr(int(a[i*2:i*2+2][::-1], 16)))
...
>>> b = ''.join(b)
>>> print b
!Ce�
>>> print repr(b)
'!Ce\x87\t'
>>> print [ord(x).__hex__() for x in b]
['0x21', '0x43', '0x65', '0x87', '0x9']
??
But I'm not sure if this is the best solution...
> Thanks,
> Rohit
HTH,
--
Felipe.
More information about the Python-list
mailing list