python decode和encode


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


得到字符的編碼

import chardet
chardet.detect(rawdata)

{'confidence': 0.98999999999999999, 'encoding': 'GB2312'}

得到默認字符:

import sys
sys.getdefaultencoding()

設置默認字符編碼:

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

發送http請求時url裏的中文需要encode,可以使用urllib

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


s爲要轉換的字符串,safe裏不進行encode的字符,若需要對url裏的中文進行encode可以用下面的方式,string.printable爲可打印字符,需要注意的是這裏的字符串需要時utf-8的編碼

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章