【发布时间】:2011-02-19 04:10:56
【问题描述】:
我有一个像 \uXXXX(表示)这样的字符串,我需要将它转换成 unicode。 我从 3rd 方服务收到它,所以 python 解释器不会转换它,我需要在我的代码中进行转换。 我如何在 Python 中做到这一点?
>>> s
u'\\u0e4f\\u032f\\u0361\\u0e4f'
【问题讨论】:
我有一个像 \uXXXX(表示)这样的字符串,我需要将它转换成 unicode。 我从 3rd 方服务收到它,所以 python 解释器不会转换它,我需要在我的代码中进行转换。 我如何在 Python 中做到这一点?
>>> s
u'\\u0e4f\\u032f\\u0361\\u0e4f'
【问题讨论】:
>>> u'\\u0e4f\\u032f\\u0361\\u0e4f'.decode('unicode-escape')
u'\u0e4f\u032f\u0361\u0e4f'
>>> print u'\\u0e4f\\u032f\\u0361\\u0e4f'.decode('unicode-escape')
๏̯͡๏
【讨论】:
AttributeError: 'str' object has no attribute 'decode'
.encode() 和 .decode() 方法支持一个有趣的 list of encodings。第二个表中的那些神奇的包括unicode_escape。
【讨论】:
Python3:
bytes("\\u0e4f\\u032f\\u0361\\u0e4f", "ascii").decode("unicode-escape")
【讨论】: