python中decode和encode的区别
来源:互联网 发布:淘宝运营托管 编辑:程序博客网 时间:2024/06/15 19:56
#-*-coding:utf-8import sys'''*首先要搞清楚,字符串在Python内部的表示是unicode编码,因此,在做编码转换时,通常需要以unicode作为中间编码,即先将其他编码的字符串解码(decode)成unicode,再从unicode编码(encode)成另一种编码。decode的作用是将其他编码的字符串转换成unicode编码,如str1.decode('gb2312'),表示将gb2312编码的字符串str1转换成unicode编码。encode的作用是将unicode编码转换成其他编码的字符串,如str2.encode('gb2312'),表示将unicode编码的字符串str2转换成gb2312编码。总得意思:想要将其他的编码转换成utf-8必须先将其解码成unicode然后重新编码成utf-8,它是以unicode为转换媒介的如:s='中文'如果是在utf8的文件中,该字符串就是utf8编码,如果是在gb2312的文件中,则其编码为gb2312。这种情况下,要进行编码转换,都需要先用decode方法将其转换成unicode编码,再使用encode方法将其转换成其他编码。通常,在没有指定特定的编码方式时,都是使用的系统默认编码创建的代码文件。如下:s.decode('utf-8').encode('utf-8')decode():是解码encode()是编码isinstance(s,unicode):判断s是否是unicode编码,如果是就返回true,否则返回false*''''''s='中文's=s.decode('utf-8') #将utf-8编码的解码成unicodeprint isinstance(s,unicode) #此时输出的就是Trues=s.encode('utf-8') #又将unicode码编码成utf-8print isinstance(s,unicode) #此时输出的就是False'''print sys.getdefaultencoding()s='中文'if isinstance(s,unicode): #如果是unicode就直接编码不需要解码 print s.encode('utf-8')else: print s.decode('utf-8').encode('gb2312')print sys.getdefaultencoding() #获取系统默认的编码reload(sys)sys.setdefaultencoding('utf8') #修改系统的默认编码print sys.getdefaultencoding()
参考文章:
0 0
- python中decode和encode的区别
- python中decode和encode的区别和联系
- python中decode和encode的使用
- python中decode和encode
- python的decode和encode
- python的decode和encode
- python 的encode和decode
- Python编码—encode和decode的区别
- python decode和encode
- python字符串的decode()和encode()
- python encode和decode的妙用
- python字符串的encode和decode
- python里面的encode和decode
- iOS中URL的encode和decode
- Python JSON decode和encode
- python encode和decode函数
- python中decode,encode跟unicode的关系(encode用法,decode用法)
- 8.python中字符串的编码和解码问题——decode/encode
- CCF题目java实现
- Android 网络操作
- svn启动
- css3.0新增属性
- Verilog HDL 学习(一)
- python中decode和encode的区别
- ui控件--label
- Android 事件分发
- Android hdpi ldpi mdpi xhdpi xxhdpi适配详解
- 深度?|?如何在TensorFlow?中用深度学习修复图像?(附论文)
- mysql异常CommunicationsException: Communications link failure的解决方案
- gdb调试代码
- Ubuntu 14.04 Web 程序开发(5)Ubuntu为Tomcat启用80端口
- 用Python搭建匿名代理池