Python3 编码,,编码encode:字


编码encode:字符串str 类型 --> 字节bytes 类型 (姑且认为是设置存储格式的过程,如有不对请批评指正)
?
解码decode: 字节类型 --> 字符串类型
?
?

>>> str1 = "a">>> type(str1)<class ‘str‘>>>> bytes1 = str1.encode(‘utf-8‘)>>> type(bytes1)<class ‘bytes‘>>>> bytes1b‘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格式编码>>> h1b‘\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 编码

评论关闭