(转)Python字符串的encode与decode isinstance
来源:互联网 发布:windows defender官网 编辑:程序博客网 时间:2024/06/06 08:55
首先要搞清楚,字符串在Python内部的表示是unicode编码,因此,在做编码转换时,通常需要以unicode作为中间编码,即先将其他编码的字符串解码(decode)成unicode,再从unicode编码(encode)成另一种编码。
decode的作用是将其他编码的字符串转换成unicode编码,如str1.decode('gb2312'),表示将gb2312编码的字符串转换成unicode编码。
encode的作用是将unicode编码转换成其他编码的字符串,如str2.encode('gb2312'),表示将unicode编码的字符串转换成gb2312编码。
在某些IDE中,字符串的输出总是出现乱码,甚至错误,其实是由于IDE的结果输出控制台自身不能显示字符串的编码,而不是程序本身的问题。
如在UliPad中运行如下代码:
s=u"中文"
print s
会提示:UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-1: ordinal not in range(128)。这是因为UliPad在英文WindowsXP上的控制台信息输出窗口是按照ascii编码输出的(英文系统的默认编码是ascii),而上面代码中的字符串是Unicode编码的,所以输出时产生了错误。
将最后一句改为:print s.encode('gb2312')
则能正确输出“中文”两个字。
若最后一句改为:print s.encode('utf8')
则输出:/xe4/xb8/xad/xe6/x96/x87,这是控制台信息输出窗口按照ascii编码输出utf8编码的字符串的结果。
Updated at: 2008.11.05
另外,代码中字符串的默认编码与代码文件本身的编码一致,如:
s='中文'
如果是在utf8的文件中,该字符串就是utf8编码,如果是在gb2312的文件中,则其编码为gb2312。 这种情况下,要进行编码转换,都需要先用decode方法将其转换成unicode编码,再使用encode方法将其转换成其他编码。通常,在没有指定特定的编码方式时,都是使用的系统默认编码创建的代码文件,在这篇文章中可以看到如何获得系统的默认编码。
如果字符串是这样定义:
s=u'中文'
则该字符串的编码就被指定为unicode了,即python的内部编码,而与代码文件本身的编码无关。因此,对于这种情况做编码转换,只需要直接使用encode方法将其转换成指定编码即可。
如果一个字符串已经是unicode了,再进行解码则将出错,因此通常要对其编码方式是否为unicode进行判断:
isinstance(s, unicode) #用来判断是否为unicode
以上转载自:http://ipie.blogbus.com/logs/19379694.html
(转)Python的类型判断:isinstance
Python可以得到一个对象的类型 ,利用type函数:
>>>lst = [1, 2, 3]
>>>type(lst)
<type 'list'>
不仅如此,还可以利用isinstance函数,来判断一个对象是否是一个已知的类型。
isinstance说明如下:
isinstance(object, class-or-type-or-tuple) -> bool
Return whether an object is an instance of a class or of a subclass thereof.
With a type as second argument, return whether that is the object's type.
The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for isinstance(x, A)
or isinstance(x, B) or ... (etc.).
其第一个参数为对象,第二个为类型名或类型名的一个列表。其返回值为布尔型。
若对象的类型与参数二的类型相同则返回True。若参数二为一个元组,则若对象类型与元组中类型名之一相同即返回True。
>>>isinstance(lst, list)
Trueisinstance(lst, (int, str, list))
True
>>>isinstance(lst, (int, str, list))
True
这也算Python的强大之一吧!
转载出处:http://blog.csdn.net/kiki113/archive/2009/05/05/4152964.aspx
- (转)Python字符串的encode与decode isinstance
- Python字符串的encode与decode
- Python字符串的encode与decode
- Python字符串的encode与decode
- Python字符串的encode与decode
- Python字符串的encode与decode
- Python字符串的encode与decode
- Python字符串的encode与decode
- Python字符串的encode与decode
- Python字符串的encode与decode
- Python字符串的encode与decode
- Python字符串的encode与decode
- Python字符串的encode与decode
- Python字符串的encode与decode
- Python字符串的encode与decode
- Python字符串的encode与decode
- Python字符串的encode与decode
- Python字符串的encode与decode
- Case中如何使用String做为判断条件
- exception setting property value with CGLIB 如何解决
- BREW应用的c++实现注意点
- IT程序员,好好规划自己的路!
- 什么是W3C标准
- (转)Python字符串的encode与decode isinstance
- 应用从PB 9.0升级到11 应该注意的问题(记录)
- Jakarta Commons Validator(转)
- css中关于超链接的四个属性一般正常顺序为:link,visited,hover,active
- VC operate FIledlg
- 堆栈的C代码实现
- js获取下拉框的值
- windows 7下无法登录飞信的解决
- Struts:页面跳转到一个action中的方法无显示,同时不报错误!