python decode和encode

来源:互联网 发布:烈焰遮天 源码 双端 编辑:程序博客网 时间:2024/05/16 18:39

http://blog.chinaunix.net/uid-27838438-id-4227131.html


得到字符的编码

import chardetchardet.detect(rawdata)
{'confidence': 0.98999999999999999, 'encoding': 'GB2312'}

得到默认字符:

import syssys.getdefaultencoding()

设置默认字符编码:

import sysreload(sys)sys.setdefaultencoding('utf-8')

发送http请求时url里的中文需要encode,可以使用urllib

import urlliburllib.quote(s, safe='/')


s为要转换的字符串,safe里不进行encode的字符,若需要对url里的中文进行encode可以用下面的方式,string.printable为可打印字符,需要注意的是这里的字符串需要时utf-8的编码

import stringurl = urllib.quote(url.encode('utf-8'), safe=string.printable)

原创粉丝点击