Python 2.7 如何打印 unicode-escape 格式字符串?

标签 python python-2.7 unicode utf-8

我知道Python中的unicode字符串,就像u“blablabla”。它应该以“u”字符开头。 但我发现了一些“unicode”,比如来自一些api的字符串,就像

{"ret":"100015","msg":"\u5bc6\u7801\u8f93\u5165\u9519\u8bef\uff0c\u8fd8\u53ef\u4ee5\u8f93\u51654\u6b21","msg_new":"\u5bc6\u7801\u8f93\u5165\u9519\u8bef<br>\u8fd8\u53ef\u4ee5\u8f93\u5165<b>4<\/b>\u6b21"}

该字符串不是以“u”字符开头,所以我想知道如何处理这些字符串?

最佳答案

对于给定的 str(在 python 3 中,字节),其字符以 \uHHHH 形式(unicode 字符转义序列)编码,可以使用 unicode-escape 编解码器对其进行解码。

>>> s = "\u5bc6\u7801\u8f93\u5165\u9519\u8bef\uff0c\u8fd8\u53ef\u4ee5\u8f93\u51654\u6b21"
>>> type(s)
<type 'str'>
>>> r = s.decode("unicode-escape")
>>> type(r)
<type 'unicode'>
>>> print(r)
密码输入错误,还可以输入4次

关于Python 2.7 如何打印 unicode-escape 格式字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33359737/

相关文章:

python - 错误: cannot run ssh: No such file or directory

python - 迭代时从集合中删除项目

python - 如何删除字符串中最后一个数字之后的所有内容

python - 如何在 Excel 的 Power Query 中运行 Python 脚本

Python 对两个列表求幂的性能

python-2.7 - Pandas/matplotlib 条形图,颜色由列定义

Python ctypes : calling a function with custom types in c

java - 使用移位操作将 Java 中的代码点转换为 utf-8 字节数组

C++:实现定义的可接受的物理源文件字符

Javascript charCodeAt 和 fromCharCode 不返回相同的值