python中decode和encode的區別

2021-09-09 04:46:48 字數 1457 閱讀 3527

import

sys'''

*字串在python內部的表示是unicode編碼,因此,在做編碼轉換時,通常需要以unicode作為中間編碼,

即先將其他編碼的字串解碼(decode)成unicode,再從unicode編碼(encode)成另一種編碼。

decode的作用是將其他編碼的字串轉換成unicode編碼,如str1.decode('gb2312'),表示將gb2312編碼的字串str1轉換成unicode編碼。

encode的作用是將unicode編碼轉換成其他編碼的字串,如str2.encode('gb2312'),表示將unicode編碼的字串str2轉換成gb2312編碼。

總得意思:想要將其他的編碼轉換成utf-8必須先將其解碼成unicode然後重新編碼成utf-8,它是以unicode為轉換媒介的

如:s='中文'

如果是在utf8的檔案中,該字串就是utf8編碼,如果是在gb2312的檔案中,則其編碼為gb2312。這種情況下,要進行編碼轉換,都需要先用

decode方法將其轉換成unicode編碼,再使用encode方法將其轉換成其他編碼。通常,在沒有指定特定的編碼方式時,都是使用的系統預設編碼建立的**檔案。

如下:s.decode('utf-8').encode('utf-8')

decode():是解碼

encode():是編碼

isinstance(s,unicode):判斷s是否是unicode編碼,如果是就返回true,否則返回false*

''''''

s='中文'

s=s.decode('utf-8') #將utf-8編碼的解碼成unicode

print isinstance(s,unicode) #此時輸出的就是true

s=s.encode('utf-8') #又將unicode碼編碼成utf-8

print isinstance(s,unicode) #此時輸出的就是false

'''print

sys.getdefaultencoding()

s='中文

'if isinstance(s,unicode): #

如果是unicode就直接編碼不需要解碼

print s.encode('

utf-8')

else

:

print s.decode('

utf-8

').encode('

gb2312')

print sys.getdefaultencoding() #

獲取系統預設的編碼

reload(sys)

sys.setdefaultencoding(

'utf8

') #

修改系統的預設編碼

print sys.getdefaultencoding()

python中decode和encode的使用

python中的編碼是採用unicode編碼的,在做編譯轉換時,需要使用unicode作為中間編碼 情況一 編碼一 unicode編碼 將其他編碼的字串解碼 decode成unicode a.decode gb2312 或者 unicode.unicode a,gb2312 情況二 unicode編...

python中decode和encode的區別

coding utf 8 import sys 首先要搞清楚,字串在python內部的表示是unicode編碼,因此,在做編碼轉換時,通常需要以unicode作為中間編碼,即先將其他編碼的字串解碼 decode 成unicode,再從unicode編碼 encode 成另一種編碼。decode的作用...

Python中的decode解碼和encode編碼

decode是解碼 讀取文字或網頁時的過程是decode解碼,需要依據文字或網頁的編碼格式來指定解碼格式。它是將不是unicode的格式解碼 換 成unicode格式讀取到記憶體中,使用時必須知道物件源格式。如str1.decode gb2312 表示將gb2312編碼的字串轉換成unicode編碼...