首页 > 解决方案 > python2中如何将str类型的unicode字符串转换为真正的unicode字符串?

问题描述

我正在尝试将 str 字符串转换'\u4e2d\u56fd'为 unicode u'\u4e2d\u56fd'。在python3中也是一样的,但是在python2.7中怎么做呢?

我尝试过 decode、encode、str、bytes、unicode 等,但它们都不起作用。

a = '\u4e2d\u56fd'
b = u'\u4e2d\u56fd'
print a
print b

上面代码的结果是

\u4e2d\u56fd
中国

我要做的就是将a转换为b。

感谢您的提示!

标签: pythonpython-2.7

解决方案


您需要使用 raw_unicode_escape 编解码器。例如:

a = '\u4e2d\u56fd'
a = a.decode('raw_unicode_escape')
print a
中国

推荐阅读