unicode转中文以及str形态的unicode转中文

今天在工作中遇到这样一个问题(工作环境为Python2.7.1),需要将一个字典中字符串形态的Unicode类型的汉字转换成中文,随便总结一下:

1、unicode转中文

old = u'\u4e2d\u56fd'
print old.encode(encoding='utf-8')
>>>>> 中国

2、str形态的unicode转中文

old = '\\u9690\\u79c1\\u7a83\\u53d6'
print old.encode('utf-8').decode('unicode_escape')
>>>>> 隐私窃取

3、认识python2和python3编码并对比

Python有两种不同的字符串,一种存储文本,一种存储字节。对于文本,python内部采用Unicode存储,而字节字符串显示原始字节序列或者ASCII。

什么叫编码(encode)?

将Unicode字符按照编码规则(如UTF-8)编成字节序列

什么叫解码(decode)?

将字节序列按照编码规则(如UTF-8)解释成unicode形式

Python2 中字符的类型:
	1、str: 已经编码后的字节序列
	2、unicode: 编码前的文本字符
import platform
print (platform.python_version())

str = '中国'
print(str,type(str))
print (str.decode('utf-8'),type(str.decode('utf-8')))


2.7.13
('\xe4\xb8\xad\xe5\x9b\xbd', <type 'str'>)
(u'\u4e2d\u56fd', <type 'unicode'>)

 

Python3 中字符的类型:
	1、str: 编码过的 unicode 文本字符
	2、bytes: 编码前的字节序列
import platform
print (platform.python_version())

str = '中国'
print(str,type(str))
print (str.encode('utf-8'),type(str.encode('utf-8')))

3.2.0
中国 <class 'str'>
b'\xe4\xb8\xad\xe5\x9b\xbd' <class 'bytes'>

在Python3中的 str 对象在Python2中叫做 unicode ,感觉很通俗对吧?但 bytes 对象在Python2中叫做 str ,总体来说,在 Python3 中,字符编码问题得到了极大的优化,不再像 Python2 那么头疼。在 Python3 中,文本总是 Unicode, 由 str 类型进行表示,二进制数据使用 bytes 进行表示,不会将 str 与 bytes 偷偷的混在一起,使得两者的区别更加明显。

 

转载于:https://www.cnblogs.com/luxiaojun/p/6930045.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值