python2.7如何解析'\\u6c5f\\u897f\\u7701\\u4e0a\\u9976\\u5730\\u533a\\u6ce2\\u9633\\u53bf'类型的字符串

遇到一个类似于“\u6c5f\u897f\u7701\u4e0a\u9976\u5730\u533a\u6ce2\u9633\u53bf”的字符串,如何直接解析出中文

解决方法:
test_str.encode(‘utf-8’).decode(“unicode-escape”)

代码如下 : test_encode.py

#coding:utf-8
import sys

test_str = '\\u6c5f\\u897f\\u7701\\u4e0a\\u9976\\u5730\\u533a\\u6ce2\\u9633\\u53bf'
print test_str
test_str_new = test_str.encode('utf-8').decode("unicode-escape")
print test_str_new

运行如上代码:python test_encode.py
在屏幕上可以输出:

\u6c5f\u897f\u7701\u4e0a\u9976\u5730\u533a\u6ce2\u9633\u53bf
江西省上饶地区波阳县

但是将输出结果写入到文件中时却报如下的错误:

$python test_encode.py > tt
Traceback (most recent call last):
  File "test_encode.py", line 7, in <module>
    print test_str_new
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-9: ordinal not in range(128)

原因:这是因为终端不支持中文显示导致的
解决方法如下:

PYTHONIOENCODING=utf-8 python test_encode.py > tt
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值