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
2010-07-19 09:33:10
Thanks a lot, it works
apple_pie
2010-07-19 09:39:27
Some of the characters don't come out right, like comma and ה and ל...
apple_pie
2010-07-19 12:20:47
@apple: What does your code look like?
KennyTM
2010-07-19 12:39:52
Ok, when I try to get hex digits, the order is scrambled up...
apple_pie
2010-07-20 22:35:17
body = "ואו הצלחתי לשלוח בעברית" body = binascii.hexlify(smart_unicode(body).encode('utf16'))
apple_pie
2010-07-20 22:35:56
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
2010-07-20 23:32:40
Eventually, the thing that worked with no further adjustments was:ucs2_body = body.encode("utf_16_be").encode("hex")
apple_pie
2010-07-21 07:42:42
@apple: Note that `.encode('hex')` is no longer available on Python 3.x.
KennyTM
2010-07-21 10:38:25