python 将unicode编码转换为汉字的几种方法

str = '\u4eac\u4e1c\u653e\u517b\u7684\u722c\u866b'
 
方法1 使用unicode_escape 解码
print str.decode('unicode_escape')
print unicode(str, 'unicode_escape')
 
方法2:若为json 格式,使用json.loads 解码
print json.loads('"%s"' %str)
 
方法3:使用eval
print eval('u"%s"' % str)
 
方法4:使用python3





总结:
1. str.encode()  把字符串转换为其raw bytes形式;bytes.decode()   把raw bytes转换为字符串形式
2. 遇到类似的编码问题时,先检查响应内容text是什么类型,
如果type(text) is bytes,那么:
   text.decode('unicode_escape')
如果type(text) is str,那么:
text.encode('latin-1').decode('unicode_escape')

猜你喜欢

转载自www.cnblogs.com/songfucai/p/9343448.html