使用Python在字符串中转义字符

时间:2011-04-05 16:19:45

标签: python json unicode escaping posterous

我发出了一个JSON请求,它为我提供了一个使用Unicode character codes的字符串,如下所示:

s = "\u003Cp\u003E"

我想将其转换为:

s = "<p>"

在Python中执行此操作的最佳方法是什么?

注意,这是与this one相同的问题,仅在Python中除了Ruby之外。我也在使用Posterous API

3 个答案:

答案 0 :(得分:16)

>>> "\\u003Cp\\u003E".decode('unicode-escape')
u'<p>'

答案 1 :(得分:10)

如果数据来自JSON,json模块应该已经为您解码了这些转义:

>>> import json
>>> json.loads('"\u003Cp\u003E"')
u'<p>'

答案 2 :(得分:1)

编辑:原始问题“Unescaping Characters in a String with Python”没有说明该字符串是编写还是be 阅读(后来添加了“JSON 响应”字样,以阐明意图是阅读 ).

所以我回答了相反的问题:如何编写 JSON 序列化数据,将它们转储为未转义的字符串(而不是从字符串加载数据)。

我的用例是从我自己的数据字典生成一个 JSON 文件,但该文件包含转义的非 ASCII 字符。所以我是这样做的:

with open(filename,'w') as jsonfile:
    jsonstr = json.dumps(myDictionary, ensure_ascii=False)
    print(jsonstr)          # to screen
    jsonfile.write(jsonstr) # to file

如果 ensure_ascii 为 true(默认值),则输出保证所有传入的非 ASCII 字符都被转义。如果 ensure_ascii 为假,这些字符将按原样输出。

取自此处:https://docs.python.org/3/library/json.html