当python加载json时,如何将str转换成unicode,这样我就可以打印汉字了?

2024-09-27 23:18:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个这样的json文件:

^{1}$

之后,我得到了一个输出:\u6b66\u6c49 我知道它是武汉汉字的unicode,但它的类型是str isinstance(cityname,str)为真。 那么我如何将这个str转换成unicode,输出将是武汉

我也尝试过这些解决方案:

^{pr2}$

搜索了一些关于ascii,unicode和utf-8的东西,编解码,但也看不懂,太疯狂了! 我需要帮助,谢谢!在


Tags: 文件json类型asciiunicode解决方案utfisinstance
1条回答
网友
1楼 · 发布于 2024-09-27 23:18:19

json包含转义的unicode字符。您可以使用unicode_escape编解码器将它们解码为实际的unicode字符:

print cityname.decode('unicode_escape')

请注意,虽然这通常可以工作,但根据unicode转义的来源,您可能会遇到基本多语言平面(U+0到U+FFFF)之外的字符的问题。我从一条评论中引用了用户@bobince的一句话:

Note that ... there are a number of different formats that use \u escapes - Python unicode literals (which unicode-escape handles), Java properties, JavaScript string literals, JSON, and so on. It is important to know which one you are dealing with because they all have slightly different rules about what other escapes are valid. unicode-escape may or may not be a valid way of parsing that data depending on where it comes from.

相关问题 更多 >

    热门问题