查看字符的编码
下载解压后把chardet目录复制到C:\Python27\Lib\site-packages 即可
chardet.detect(str)
python内部用的是unicode编码,
因此在做编码转化的时候,先将源编码的字符串解码(decode)成unicode,再从unicode编码(encode)成目标编码转码的时候一定要先搞明白,字符串str是什么编码
比如这次从xls文件里读出来的中文, 用
.encode('gbk')就可以正常显示
查看str的编码形式
str.__class__
查看系统默认的编码
print sys.getdefaultencoding() 指定默认的字符编码
#coding=utf-8
import sys
reload(sys)
sys.setdefaultencoding('gbk')
另一个方案是在python的Lib\site-packages文件夹下新建一个sitecustomize.py,内容为:
#coding=utf-8
import sys
reload(sys)
sys.setdefaultencoding('gbk')
SQLlite3插入中文字段时报错
You must not use 8-bit bytestrings unless you use a text_factory...
有两种方法解决:
第一种,设置text_factory = str
users = ('腾讯qq', 'qq@example.com')
conn = sqlite3.connect(dbname)
conn.text_factory = str ##!!!
第二种,把插入的数据转换为unicode:
users = ('腾讯qq'.decode('utf8'), 'qq@example.com')
conn = sqlite3.connect(dbname)
cursor = conn.cursor()
URL编码
编码:urllib.quote(string[, safe]),除了三个符号“_.-”外,将所有符号编码,后面的参数safe是不编码的字符,
使用的时候如果不设置的话,会将斜杠,冒号,等号,问号都给编码了。
设置不编码的符号:
>>> print urllib.quote(urlstr,":?=/")