jack jack - 1 year ago 139
Python Question

Python Unicode Conversions

How to do the following conversions in Python?

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

Answer Source

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'))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download