字符编码转换问题:
python 中系统默认使用unicode编码,所有非unicode编码格式之间转换必须通过unicode为中介。 非unicode通过decode转换为unicode编码格式,unicode编码格式通过decode转换为指定的任意编码格式。
下面是不同字符编码之间转换的示例
1 # -*- coding:utf-8 -*- 2 import sys 3 print(sys.getdefaultencoding()) 4 str1 = "欢迎来到字符编码章节" 5 print(str1) 6 str1_to_gbk = str1.encode("gbk") #将unicode转换为gbk格式,python3中进行编码转换时会以byte类型显示 7 print('str1_to_gbk:',str1_to_gbk) 8 str_gbk = str1_to_gbk 9 str_gbk_to_utf_8 = str_gbk.decode("gbk").encode("utf-8") #gbk转换为utf-8 10 print('str_gbk_to_utf_8:',str_gbk_to_utf_8) 11 print("转换byte类型utf-8为str类型:",str(str_gbk_to_utf_8)) #str强制转换不过来 12 str_gbk_to_gb2312 = str_gbk.decode("gbk").encode("gb2312") #gbk转换为gb2312 13 print('str_gbk_to_gb2312:',str_gbk_to_gb2312) 14 print(str_gbk_to_gb2312.decode("gb2312")) #将db2312编码格式解码输出
str/bytes类型之间转换简析
Python 3最重要的新特性大概要算是对文本和二进制数据作了更为清晰的区分。文本总是Unicode,由str类型表示,二进制数据则由bytes类型表示。
python3中只要对str进行encode操作,默认会将其转换为bytes类型。即Unicode表示的str通过encode()方法可以编码为指定的bytes。
如果我们从网络或磁盘上读取了字节流,那么读到的数据就是bytes。要把bytes变为str,就需要用decode()方法。
1 1 a = 123 2 2 print(type(a)) 3 3 b=str(a) 4 4 print(type(b)) 5 5 c=bytes(b) #使用bytes内置函数进行数据类型强制转换,必须指定str类型的编码格式,否则会报错。 6 6 print(type(c))