首先要明确一点就是python中的字符串在内部都是以unicode存储的。decode的意思是把一个unicode字符串”解码“成期望的编码,decode完后,不仅编解码变了,而且该字符串会从unicode类型的字符串变成普通的str字符串;而encode相反,意思是把一个非unicode字符串“编码”成unicode,encode完后,不仅编解码变了,而且该字符串会从普通的str字符串变成unicode类型的字符串。
#!/usr/bin/env python
# -*- coding: utf8 -*-
s1 = '普通str字符串,utf8编码'
print type(s1)
print s1.decode('utf8').encode('cp936')
s3 = u'unicode字符串被变成普通str字符串,编码变成cp936的了'
print type(s3)
s4= s3.encode('cp936')
print type(s4)
print s4
-----------------------------------------------------
<type 'str'>
普通str字符串,utf8编码
<type 'unicode'>
<type 'str'>
unicode字符串被变成普通str字符串,编码变成cp936的了