python encode和decode的妙用

字符串解码:

有个字符串:

'\\u4fee\\u6539\\u8282\\u70b9\\u72b6\\u6001\\u6210\\u529f'

想转换为:

u"\u4fee\u6539\u8282\u70b9\u72b6\u6001\u6210\u529f"

可以通过如下

>>> a = '\\u4fee\\u6539\\u8282\\u70b9\\u72b6\\u6001\\u6210\\u529f'

>>> a.decode('unicode_escape')

u'\u4fee\u6539\u8282\u70b9\u72b6\u6001\u6210\u529f'

字符串转换为16进制:

>>> "hello".encode("hex")

'68656c6c6f'

相应的还可以

>>> '68656c6c6f'.decode("hex")

'hello'

可以检查下手册,看看哪些codec可用


上一篇:Python实用技巧总结
下一篇:Python GUI开发工具选择

PythonTab微信公众号:

Python技术交流互助群 ( 请勿加多个群 ):

群1: 87464755

群2: 333646237

群3: 318130924

群4: 385100854