jack jack - 4 months ago 17
Python Question

Python Unicode Conversions

How to do the following conversions in Python?

"杭州" to "%BA%BC%D6%DD"
"大连" to "%B4%F3%C1%AC"

Answer

To convert u'杭州' to '%BA%BC%D6%DD':

In [24]: ''.join('%{0:X}'.format(ord(c)) for c in u"杭州".encode('gbk'))
Out[24]: '%BA%BC%D6%DD'

In [25]: ''.join('%{0:X}'.format(ord(c)) for c in u"大连".encode('gbk'))
Out[25]: '%B4%F3%C1%AC'

To convert '%BA%BC%D6%DD' to u'杭州':

In [54]: import binascii    
In [55]: print(binascii.unhexlify(''.join('%BA%BC%D6%DD'.split('%'))).decode('gbk'))
杭州
Comments