---
title: "python"
author: "wjg_java"
date: "2017-11-27T23:42:00Z"
tags: []
categories: ["编程语言"]
slug: "python"
draft: false
lastmod: "2017-11-27T23:42:00Z"
id: 2401067
url: "https://wjg-java.iteye.com/blog/2401067"
---

<http://blog.csdn.net/moodytong/article/details/8136258>

字符串编码常用类型：utf-8,gb2312,cp936,gbk等。

python中，我们使用decode()和encode()来进行解码和编码

在python中，使用unicode类型作为编码的基础类型。即

     decode              encode

str ---------> unicode --------->str

u = u'中文' #显示指定unicode类型对象u
str = u.encode('gb2312') #以gb2312编码对unicode对像进行编码
str1 = u.encode('gbk') #以gbk编码对unicode对像进行编码
str2 = u.encode('utf-8') #以utf-8编码对unicode对像进行编码
u1 = str.decode('gb2312')#以gb2312编码对字符串str进行解码，以获取unicode
u2 = str.decode('utf-8')#如果以utf-8的编码对str进行解码得到的结果，将无法还原原来的unicode类型
如上面代码，str\str1\str2均为字符串类型（str）,给字符串操作带来较大的复杂性。

好消息来了，对，那就是python3，在新版本的python3中，取消了unicode类型，代替它的是使用unicode字符的字符串类型(str),字符串类型（str）成为基础类型如下所示，而编码后的变为了字节类型(bytes)但是两个函数的使用方法不变：

     decode              encode

bytes ------> str(unicode)------>bytes

u = '中文' #指定字符串类型对象u
str = u.encode('gb2312') #以gb2312编码对u进行编码，获得bytes类型对象str
u1 = str.decode('gb2312')#以gb2312编码对字符串str进行解码，获得字符串类型对象u1
u2 = str.decode('utf-8')#如果以utf-8的编码对str进行解码得到的结果，将无法还原原来的字符串内容