python中decode和encode的区别和联系

编码问题:decode和encode的区别和联系
python中,我们使用decode()和encode()来进行解码和编码。使用unicode类型作为编码的基础类型。即

str —-(decode)—–> unicode —–(encode)—->str

  • 字符串在python内部的表示是unicode编码,因此,在做编码转换时,通常需要以unicode作为中间编码,即先将其他编码的字符串解码(decode)成unicode,再从unicode编码(encode)成另一种编码。

  • decode的作用是将其他编码的字符串转换成unicode编码,如str1.decode(‘gb2312’),表示将gb2312编码的字符串转换成unicode编码。

  • encode的作用是将unicode编码转换成其他编码的字符串,如str2.encode(‘gb2312’),表示将unicode编码的字符串转换成gb2312编码。

例子:

>>> str = '你好世界'
>>> print str
你好世界
>>> type(str)
<type 'str'>

#字符串转为Unicode
>>> str =u'你好,世界'
>>> type(str)
<type 'unicode'>

>>> len(str)
5

#将Unicode编码转为utf-8编码
>>> str.encode('utf-8')
'\xe4\xbd\xa0\xe5\xa5\xbd\xef\xbc\x8c\xe4\xb8\x96\xe7\x95\x8c'

#utf-8编码,一个汉字占用两个字节;GBK编码一个汉字占用一个字节
>>> len(str.encode('utf-8'))
15

#将utf-8编码的字符串解码为Unicode
>>> str.decode('utf-8')
u'\u4f60\u597d\uff0c\u4e16\u754c'

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值