首页 > 编程语言 > 详细

Python3 编码

时间:2020-03-21 22:34:21      阅读:70      评论:0      收藏:0      [点我收藏+]
编码encode:字符串str 类型 --> 字节bytes 类型 (姑且认为是设置存储格式的过程,如有不对请批评指正)
?
解码decode: 字节类型 --> 字符串类型
?
?

>>> str1 = "a"
>>> type(str1)
<class ‘str‘>
>>> bytes1 = str1.encode(‘utf-8‘)
>>> type(bytes1)
<class ‘bytes‘>
>>> bytes1
b‘a‘

?
?


区分字符串前的b与u:

1.无前缀?&?u前缀(str对象)
?字符串默认创建即以Unicode编码存储,可以存储中文。
?
? string?=?‘a‘??等效于??string?=?u‘a‘
?Unicode中通常每个字符由2个字节表示
u‘a‘?即?? ?u‘\u0061‘? ?实际内存中为 ?[0000?0000]?[0110?0001]
?
?
2.b前缀(bytes对象)
? ?字符串存储为Ascll码,无法存储中文。
?
?每个字符由1个字节表示(8位)?
?b‘a‘ 即?b‘\x61‘? 实际内存中为?[0110?0001]?
?

 >>> a = b‘hello‘
>>> b = u‘hello‘
>>> type(a)
<class ‘bytes‘>
>>> type(b)
<class ‘str‘>

?

>>> h = "中国"
>>> h1 = h.encode(‘utf-8‘)   # 将字符串以utf-8格式编码
>>> h1
b‘\xe4\xb8\xad\xe5\x9b\xbd‘
>>> h1.decode(‘ascii‘)   # 中文无法用ascii格式编码
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: ‘ascii‘ codec can‘t decode byte 0xe4 in position 0: ordinal not in range(128)
>>> h1.decode(‘utf-8‘)  # 将字节对象以utf-8的方式解码
‘中国‘

Python3 编码

原文:https://blog.51cto.com/jackor/2480634

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!