您的位置:首页 > 编程语言 > Python开发

Python 之 字符转编码操作

2019-01-23 11:16 447 查看

字符转编码操作

# -*- coding:utf-8 -*-
import sys
print(sys.getdefaultencoding())

s = "你好"

python2写法,将s转换成"gbk"

s_to_gbk = s.decode("utf-8").encode("gbk")

#1.在Python2下,所有字符编码为"ascii"
#2.当文件头声明定义为:utf-8
#3.将s转换gbk,首先将s解码成utf-8: s.decode("utf-8"),utf-8其实就是unicode的扩展,所以后面可直接编码。
#4.将s从utf-8编码成gbk,s.decode("utf-8").encode("gbk")

Python3写法,将s转换成“gbk"

s_to_gbk = s.encode("gbk")

#1.在Python3下,所有字符编码为"utf-8"(unicode)
#2.将s解码成gbk, s.encode("gbk")

#备注:Python2 与 Python3 区别:
#1. Python2 的字符默认为ASCII , Python3 的字符默认为utf-8(unicode)
#2. 因所有字符编码之间的转换都需要经过unicode,所以python2 比python3 多了一个步骤。

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Python