python---字符编码与转码
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python---字符编码与转码相关的知识,希望对你有一定的参考价值。
1.在python2:
#-*- coding:utf-8 -*- import sys print(sys.getdefaultencoding()) #获取系统默认编码 #1.utf-8转gbk s = "你好" s_to_unicode = s.decode("utf-8") #将utf-8类型转换为unicode print(s_to_unicode) print(type(s_to_unicode)) s_to_gbk = s.decode("utf-8").encode("gbk") #utf-8转gbk:将utf-8先decode成unicode,在encode成gbk print(s_to_gbk) #注:unicode可以直接打印utf-8编码字符 #2.gbk转utf-8 gbk_to_utf8 = s_to_gbk.decode("gbk").encode("utf-8") print(gbk_to_utf8)
2.在python:
import sys print(sys.getdefaultencoding()) #获取系统默认编码utf-8(忽略) msg = "你好" #默认就是unicode,不用再decode print(msg) msg_gb2312 = msg.encode("gb2312") #unicode转成gb2312,转成gb2312的同时会转成bytes类型 print(msg_gb2312) gb2312_to_unicode = msg_gb2312.decode("gb2312") #gb2312转unicode print(gb2312_to_unicode) gb2312_to_utf8 = msg_gb2312.decode("gb2312").encode("utf-8") #gb2312转utf-8,转成utf-8的同时会转成bytes类型 print(gb2312_to_utf8)
以上是关于python---字符编码与转码的主要内容,如果未能解决你的问题,请参考以下文章