python之编码

解决python2在cmd下显示中文乱码问题

编码解码关系如图:

在我们写python代码时,首行会写上#coding:utf-8  指代码内容是用utf-8编码的,在Linux上运行没有问题

但在cmd下会不能正常显示,因为cmd默认编码为gbk

如:

#coding:utf-8

temp = '你好'
print 'temp:',temp

结果如下:

 

为了使其在cmd下正常显示,不乱码,我们只需通过上图关系,将需要打印的字符串转为gbk

 

#coding:utf-8

temp = '你好'
print 'temp:',temp

#unicode
temp_uni = temp.decode('utf-8')

#gbk
temp_gbk = temp_uni.encode('gbk')

print 'gbk:',temp_gbk

结果如下图:

 另外,在python2中,我们将utf-8解码为unicode输出时,windows会自动输出其想要的编码(gbk)

如:

#coding:utf-8

temp = '你好'
print 'temp_unicode:',temp.decode('utf-8')

结果:

******************************************************

在python3中,字符串不能decode了,直接输出即可

#coding:utf-8

temp = '你好'
print('temp:',temp)

 

posted @ 2017-04-13 00:29  Garvey  阅读(30)  评论(0)    收藏  举报