1. 程式人生 > 其它 >python encode與decode

python encode與decode

encode()和decode()

  • decode英文意思是 解碼,encode英文原意 編碼
  • 字串在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方法將其轉換成其他編碼。通常,在沒有指定特定的編碼方式時,都是使用的系統預設編碼建立的程式碼檔案