python转义符号怎么用_用python转换转义字符

First sorry for my english

I have to convert strings from a json file like the following:

{"detalle":"el Expediente N\u00b0\u00a030 de la Resoluci\u00f3n 11..."}

In something like:

{"detalle":"el Expediente N° 30 de la Resolución 11..."}

to then write it in a txt.

I tried:

json.dumps({"detalle":"el Expediente N\u00b0\u00a030 de la Resoluci\u00f3n 11..."}, ensure_ascii=False).encode('utf8')

that returns

'{"detalle": "el Expediente N\\\\u00b0\\\\u00a030 de la Resoluci\\\\u00f3n 11..."}'

How can I convert it?

解决方案

(In this answer, I'm assuming you use Python 2.)

First, let me explain why your snippet returns something different than you expect:

r1 = json.dumps({"detalle":"el Expediente N\u00b0\u00a030 de la Resoluci\u00f3n 11..."}, ensure_ascii=False).encode('utf8')

print(r1)

r2 = json.dumps({"detalle":u"el Expediente N\u00b0\u00a030 de la Resoluci\u00f3n 11..."}, ensure_ascii=False).encode('utf8')

print(r2)

This outputs:

{"detalle": "el Expediente N\\u00b0\\u00a030 de la Resoluci\\u00f3n 11..."}

{"detalle": "el Expediente N° 30 de la Resolución 11..."}

The difference is, that in the first case, the input string is ascii code, with slashes and other characters to represent special characters, and in the second case, the string is a unicode string with unicode characters. The second case is what you want.

Based on this, here is what I understand from your problem:

Normally when you read a JSON file with the json module, the strings (which are escaped in the JSON file) are unescaped by the parser. If you still see escaped characters, that indicates that the strings were (accidentally?) double escaped in the JSON file. In that case, try an extra unescape with s.decode('unicode-escape'):

data["detalle"] = data["detalle"].decode('unicode-escape')

Once you have proper unicode strings loaded in Python, converting them to bytes with s.encode('utf8') and writing the result to a file, is correct.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值