我知道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/