1. 程式人生 > >python中encode()函式的用法

python中encode()函式的用法

python字串函式用法大全連結

encode()函式

描述:以指定的編碼格式編碼字串,預設編碼為 'utf-8'。

語法:str.encode(encoding='utf-8', errors='strict')     -> bytes (獲得bytes型別物件)

  • encoding 引數可選,即要使用的編碼,預設編碼為 'utf-8'。字串編碼常用型別有:utf-8,gb2312,cp936,gbk等。
  • errors 引數可選,設定不同錯誤的處理方案。預設為 'strict',意為編碼錯誤引起一個UnicodeEncodeError。 其它可能值有 'ignore', 'replace', 'xmlcharrefreplace'以及通過 codecs.register_error() 註冊其它的值。

程式示例:

str1 = "我愛祖國"
str2 = "I love my country"
print("utf8編碼:",str1.encode(encoding="utf8",errors="strict")) #等價於print("utf8編碼:",str1.encode("utf8"))
print("utf8編碼:",str2.encode(encoding="utf8",errors="strict"))
print("gb2312編碼:",str1.encode(encoding="gb2312",errors="strict"))#以gb2312編碼格式對str1進行編碼,獲得bytes型別物件的str
print("gb2312編碼:",str2.encode(encoding="gb2312",errors="strict"))
print("cp936編碼:",str1.encode(encoding="cp936",errors="strict"))
print("cp936編碼:",str2.encode(encoding="cp936",errors="strict"))
print("gbk編碼:",str1.encode(encoding="gbk",errors="strict"))
print("gbk編碼:",str2.encode(encoding="gbk",errors="strict"))

程式執行結果:

utf8編碼: b'\xe6\x88\x91\xe7\x88\xb1\xe7\xa5\x96\xe5\x9b\xbd'
utf8編碼: b'I love my country'
gb2312編碼: b'\xce\xd2\xb0\xae\xd7\xe6\xb9\xfa'
gb2312編碼: b'I love my country'
cp936編碼: b'\xce\xd2\xb0\xae\xd7\xe6\xb9\xfa'
cp936編碼: b'I love my country'
gbk編碼: b'\xce\xd2\xb0\xae\xd7\xe6\xb9\xfa'
gbk編碼: b'I love my country'

注:在python中encodedecode分別指編碼和解碼