encode与decode,中文乱码

https://blog.csdn.net/Y601343678/article/details/78585728 p> 

如何获得系统的默认编码?

#!/usr/bin/env python

#coding=utf-8

import sys

printsys.getdefaultencoding()

该段程序在英文WindowsXP上输出为:ascii

该段程序在英文Windows7上输出为:mbcs

在UliPad中运行如下代码:

s=u"中文"

print s

扫描二维码关注公众号,回复: 6841819 查看本文章

会提示:UnicodeEncodeError:'ascii' codec can't encode characters in position 0-1: ordinal notinrange(128)。

这是因为UliPad在英文WindowsXP上的控制台信息输出窗口是按照ascii编码输出的(英文系统的默认编码是ascii),

而上面代码中的字符串是Unicode编码的,所以输出时产生了错误。

将最后一句改为:prints.encode('gb2312')

则能正确输出“中文”两个字。

若最后一句改为:prints.encode('utf8')

则输出:\xe4\xb8\xad\xe6\x96\x87,

这是控制台信息输出窗口按照ascii编码输出utf8编码的字符串的结果。

unicode(str,'gb2312')与str.decode('gb2312')是一样的,都是将gb2312编码的str转为unicode编码

使用str.__class__可以查看str的编码形式

猜你喜欢

转载自www.cnblogs.com/heluobing/p/11229255.html