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() 註冊其它的值。
程序示例:spa
>>>str1 = "我愛祖國" >>>str2 = "I love my country" >>>str1_utf8 = str1.encode(encoding="utf-8", errors="strict") >>>str2_utf8 = str2.encode(encoding="utf-8", errors="strict") >>>print("utf-8編碼:", str1_utf8) utf-8編碼: b'\xe6\x88\x91\xe7\x88\xb1\xe7\xa5\x96\xe5\x9b\xbd' >>>print("utf-8編碼:", str2_utf8) utf-8編碼: b'I love my country' >>>str1_gb2312 = str1.encode(encoding="gb2312", errors="strict") >>>str2_gb2312 = str2.encode(encoding="gb2312", errors="strict") >>>print("gb2312編碼:", str1_gb2312) gb2312編碼: b'\xce\xd2\xb0\xae\xd7\xe6\xb9\xfa' >>>print("gb2312編碼:", str2_gb2312) gb2312編碼: b'I love my country' >>>str1_cp936 = str1.encode(encoding="cp936", errors="strict") >>>str2_cp936 = str2.encode(encoding="cp936", errors="strict") >>>print("cp936編碼:", str1_cp936) cp936編碼: b'\xce\xd2\xb0\xae\xd7\xe6\xb9\xfa' >>>print("cp936編碼:", str2_cp936) cp936編碼: b'I love my country' >>>str1_gbk = str1.encode(encoding="gbk", errors="strict") >>>str2_gbk = str2.encode(encoding="gbk", errors="strict") >>>print("gbk編碼:", str1_gbk) gbk編碼: b'\xce\xd2\xb0\xae\xd7\xe6\xb9\xfa' >>>print("gbk編碼:", str2_gbk) gbk編碼: b'I love my country' >>>str1_utf8.decode('utf-8') '我愛祖國' >>>str1_gb2312.decode("gb2312") '我愛祖國' >>>str1_cp936.decode("cp936") '我愛祖國' >>>str1_gbk.decode("gbk") '我愛祖國' >>>str2_utf8.decode("utf-8") 'I love my country'
原文:https://blog.csdn.net/qq_40678222/article/details/83033492 .net
版權聲明:本文爲博主原創文章,轉載請附上博文連接!code