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

会提示: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的编码形式

转载于:https://www.cnblogs.com/heluobing/p/11229255.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值