python中编码问题——unicode, gbk, utf8

时间:2021-06-23 14:14:06

1.默认编码类型

>>> import sys
>>> sys.getdefaultencoding()
'utf-8'
python 3.4默认为utf-8编码,python 3.4默认为Ascii编码
2. Python3 中字符串的类型
bytearray ([ source[,  encoding[,  errors]]] )

Return a new array of bytes. The bytearray type is a mutable sequence of integers in the range 0 <= x < 256. 

bytes ([ source[,  encoding[,  errors]]] )

Return a new “bytes” object, which is an immutable sequence of integers in the range 0 <= x < 256bytes is an immutable version of bytearray.

str ([ object[,  encoding[,  errors]]] )

Return a string version of an object. str默认为unicode的字符串。

3.实例 

>>> us = "中国"
>>> bs = b'AAA'
>>> bs2 = bytes('中国','gbk')
>>> print(us + ':' + str(type(us)))
中国:<class 'str'>
>>> print(bs) #b'AAA'
b'AAA'
>>> print(bs2)
b'\xd6\xd0\xb9\xfa'
>>> print(':' + str(type(bs2)))
:<class 'bytes'>
>>> print(bs2.decode('gbk')) #中国
中国
>>>

三 总结

1) Python 3会假定我们的源码 — 即.py文件 — 使用的是UTF-8编码方式。Python 2里,.py文件默认的编码方式为ASCII。可以使用# -*- coding: windows-1252 -*-方式来改变文件的编码。如果py文件中包含中文的字符串,则需要制定为# -*- coding: gbk -*-,貌似默认的utf8不够哦。

2) python3中默认的str为unicode的,可以使用str.encode来转为bytes类型。

3) python3的print函数只支持unicode的str,貌似没有对bytes的解码功能,所以对对不能解码的bytes不能正确输出。 

4) str和bytes不能连接和比较。 

5) codecs任然可以用来str和bytes间的转化。 

6) 定义非ascii码的bytes时,必须使用如 bytes('中国','gbk') 来转码。