Python will default to ASCII as standard encoding if no other encoding hints are given.
# coding=
# -*- coding:
中文 coding:cp936
文件中指定的编码要和实际相符合,否则的话python会报错
Python’s tokenizer/compiler combo will need to be updated to
work as follows:
1. read the file
2. decode it into Unicode assuming a fixed per-file encoding
3. convert it into a UTF-8 byte string
4. tokenize the UTF-8 content
5. compile it, creating Unicode objects from the given Unicode data
and creating string objects from the Unicode literal data
by first reencoding the UTF-8 data into 8-bit string data
using the given file encoding
字符串在Python内部的表示是unicode编码,因此,在做编码转换时,通常需要以unicode作为中间编码,即先将其他编码的字符串解码(decode)成unicode,再从unicode编码(encode)成另一种编码。
decode的作用是将其他编码的字符串转换成unicode编码,如str1.decode(’gb2312′),表示将gb2312编码的字符串str1转换成unicode编码。
encode的作用是将unicode编码转换成其他编码的字符串,如str2.encode(’gb2312′),表示将unicode编码的字符串str2转换成gb2312编码。
因此,转码的时候一定要先搞明白,字符串str是什么编码,然后decode成unicode,然后再encode成其他编码
代码中字符串的默认编码与代码文件本身的编码一致。
如:s=’中文’
如果是在utf8的文件中,该字符串就是utf8编码,如果是在gb2312的文件中,则其编码为gb2312。
如果字符串是这样定义:s=u’中文’
则该字符串的编码就被指定为unicode了,即python的内部编码,而与代码文件本身的编码无关。
如果一个字符串已经是unicode了,再进行解码则将出错,因此通常要对其编码方式是否为unicode进行判断:
isinstance(s, unicode) #用来判断是否为unicode
用非unicode编码形式的str来encode会报错
unicode(str,’gb2312′)与str.decode(’gb2312′)是一样的,都是将gb2312编码的str转为unicode编码
如何获得系统的默认编码?
import sys
print sys.getdefaultencoding()
#!/usr/bin/env python
#coding=utf-8
s=”中文”
if isinstance(s, unicode):
#s=u”中文”
print s.encode(’gb2312′)
else:
#s=”中文”
print s.decode(’utf-8′).encode(’gb2312′)
在window下面用记事本编辑文件的时候,如果保存为UNICODE或UTF-8,分别会在文件的开头加上两个字节“\xFF\xFE”和三个字节“\xEF\xBB\xBF”。
Python中有两种默认的字符串:str和unicode。
控制台,中文字符的编码是GBK
在Python中,“str”对象就是一个字节数组,至于里面的内容是不是一个合法的字符串,以及这个字符串采用什么编码(gbk, utf-8, unicode)都不重要。这些内容需要用户自己记录和判断。这些的限制也同样适用于“unicode”对象。要记住“unicode”对象中的内容可绝对不一定就是合法的unicode字符串,我们很快就会看到这种情况。
在windows的控制台上,支持gbk编码的str对象和unicode编码的unicode对象。
windows下的IDLE SHELL中,对于不使用“u”作标识的字符串,IDLE把其中的中文字符进行GBK编码。但是对于使用“u”的unicode字符串,IDLE居然一样是用了GBK编码,不同的是,这时候每一个字符都是unicode(对象)字符!!此时len(“中文”) = 4。
参考:http://www.sqlite.com.cn/MySqlite/11/395.Html
http://blog.csdn.net/lxdcyh/archive/2009/03/23/4018054.aspx
RSS feed for comments on this post · TrackBack URI
Leave a reply