1.在python2:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
#-*- 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:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
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)
|
本文转自 fxl风 51CTO博客,原文链接:http://blog.51cto.com/fengxiaoli/2066127