python---字符編碼與轉碼

1.在python2:
python

$QBL39VI5_~X6`CUUJT(4J2.png

#-*- 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:ide

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)
相關文章
相關標籤/搜索