本文共 1430 字,大约阅读时间需要 4 分钟。
python3默认编码unicode,python2默认编码ascii。 utf8向下兼容unicode,即utf8是unicode的扩容
# python3默认编码unicodestr_unicode = "中国"# 转成gbkstr_to_gbk = str_unicode.encode('gbk')print(str_to_gbk)
输入的结果:
b'\xd6\xd0\xb9\xfa'
# decode("gbk")把gbk编码文本格式转换成str,再有str设置成utf8编码gbk_to_utf = str_to_gbk.decode("gbk").encode("utf8")print(gbk_to_utf)
输入的结果:
b'\xe4\xb8\xad\xe5\x9b\xbd'
bytes ------decode() -------> str ------encode()------->bytes
注:python 3中的str类型对象有点像Python2中的unicode,而decode是将str转为unicode编码,所以str仅有一个encode方法,调用这个方法后将产生一个编码后的byte类型的字符。# python2默认编码ascii#-*-coding:utf-8str_code="中国"print(str_code)str_to_gbk=str_code.encode("gbk")
输入报错
# python2默认编码ascii,又#-*-coding:utf-8表示文本编码格式为utf8格式;# 如果utf8直接编码为gbk会报错,应该先解码unicode格式再进行转换中国Traceback (most recent call last): File "encode.py", line 4, instr_to_gbk=str_code.encode("gbk")UnicodeDecodeError: 'ascii' codec can't decode byte 0xe4 in position 0: ordinal not in range(128)
#-*-coding:utf-8str_code="中国"print(str_code)str_to_gbk = str_code.decode("utf-8").encode("gbk")print(str_to_gbk,type(str_to_gbk))
输入的结果:
中国('\xd6\xd0\xb9\xfa',)
str_to_utf8 = str_to_gbk .decode("gbk").encode("utf8")print(str_to_utf8)
输入的结果:
中国
str ----decode() -------> unicode ----encode()------>str
注:python2中,不能直接打印unicode编码,需要将unicode转换成str才能进行打印输出,否则会报错。转载地址:http://ypzsi.baihongyu.com/