views:

40

answers:

1

Hi Guys, I've been searching for this one and couldn't find it, although it seems simple. I need to send in a ucs2 hex string in the url, and I don't know how to convert a python string to be ucs2 hex. Any thoughts?

+2  A: 
>>> 'åéîøü'.encode('utf16')
b'\xff\xfe\xe5\x00\xe9\x00\xee\x00\xf8\x00\xfc\x00'

(Note that there's a BOM in the beginning. Use the encoding 'utf_16_be' or 'utf_16_le' if the endian is fixed.)

If you need hex digits, use binascii.hexlify.

>>> import binascii
>>> binascii.hexlify('åéîøü'.encode('utf16'))
b'fffee500e900ee00f800fc00'
KennyTM
Thanks a lot, it works
apple_pie
Some of the characters don't come out right, like comma and ה and ל...
apple_pie
@apple: What does your code look like?
KennyTM
Ok, when I try to get hex digits, the order is scrambled up...
apple_pie
body = "ואו הצלחתי לשלוח בעברית" body = binascii.hexlify(smart_unicode(body).encode('utf16'))
apple_pie
ok, I managed to solve it, thanks. BTW, when you use this you need to switch the order of the hex chars (05d0 comes out d005) and if you mix spaces and latin letters you need to handle them seperately since they occupy only one char instead of two.
apple_pie
Eventually, the thing that worked with no further adjustments was:ucs2_body = body.encode("utf_16_be").encode("hex")
apple_pie
@apple: Note that `.encode('hex')` is no longer available on Python 3.x.
KennyTM